twitterinternalapi

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

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

Go to latest
Published: Mar 9, 2026 License: MIT Imports: 19 Imported by: 0

README

Twitter Internal API

GitHub go.mod Go version Go Reference Go Report Card

A lightweight Go client to interact with the internal Twitter API used on the web version, with just your auth_token and ct0 cookies.

Originally built for Miwa.lol, this package is open for anyone to use and contribute to.

Installation

go get github.com/miwalol/twitter-internal-api

Quick Start

package main

import (
	"log"
	"github.com/miwalol/twitter-internal-api"
)

func main() {
	client := twitterinternalapi.NewClient("your-auth-token", "your-csrf-token")
	
	tweet, err := client.Tweets.Create("Hello from Go!", nil)
	if err != nil {
		log.Fatal(err)
	}
	
	log.Println("Tweet ID:", tweet.ID)
	log.Println("Tweet Text:", tweet.Legacy.FullText)
}

Usage Examples

Authentication
import "github.com/miwalol/twitter-internal-api"

// Create a client with auth token and CSRF token
client := twitterinternalapi.NewClient(
	"your-bearer-token-here",
	"your-csrf-token-here",
)

// Set cookies if needed
client.SetCookies("auth_token=xxx; ct0=yyy")

// Set additional CSRF token
client.SetCSRFToken("your-csrf-token")

// Register a callback for when ct0 is refreshed (e.g. to persist it)
client.OnCSRFRefreshed(func(newToken string) {
	// save newToken to cache, database, etc.
})
Creating Tweets
// Simple tweet
tweet, err := client.Tweets.Create("Hello Twitter!", nil)
if err != nil {
	log.Fatal(err)
}
log.Println("Posted:", tweet.ID, tweet.Legacy.FullText)

// Tweet with sensitivity flag
opts := &twitterinternalapi.CreateTweetOptions{
	Sensitive: true,
}
tweet, err := client.Tweets.Create("Sensitive content", opts)
Uploading Media
// Upload from a file path
mediaID, err := client.UploadMedia("path/to/image.png", "image/png")
if err != nil {
	log.Fatal(err)
}

// Upload from a byte slice
data, _ := os.ReadFile("path/to/image.png")
mediaID, err := client.UploadMediaBytes(data, "image/png")
if err != nil {
	log.Fatal(err)
}

// Create tweet with uploaded media
opts := &twitterinternalapi.CreateTweetOptions{
	MediaEntities: []twitterinternalapi.MediaEntity{
		{MediaID: mediaID, TaggedUsers: []interface{}{}},
	},
}
tweet, err := client.Tweets.Create("Posted with image!", opts)
Deleting Tweets
// Delete a tweet by ID
err := client.Tweets.Delete("2031054061076685198")
if err != nil {
	log.Fatal(err)
}
log.Println("Tweet deleted")
GraphQL Requests

For advanced use cases, you can make custom GraphQL queries:

variables := map[string]interface{}{
	"tweet_text": "Custom query",
}

features := map[string]bool{
	"responsive_web_edit_tweet_api_enabled": true,
}

result, err := client.ExecuteGraphQL(
	variables,
	"sb6vH7FMb090KdK6IZaakw", // queryId
	"CreateTweet",              // operationName
	features,
)
if err != nil {
	log.Fatal(err)
}
log.Println(result)

License

MIT License - see LICENSE

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IntPtr

func IntPtr(i int) *int

IntPtr returns a pointer to an int.

func StringPtr

func StringPtr(s string) *string

StringPtr returns a pointer to a string.

Types

type Client

type Client struct {
	Tweets *TweetsService
	// contains filtered or unexported fields
}

Client represents a Twitter API client authenticated with a token.

func NewClient

func NewClient(authToken, csrfToken string) *Client

NewClient creates a new Twitter API client with the given auth token.

func (*Client) ExecuteGraphQL

func (c *Client) ExecuteGraphQL(
	variables map[string]interface{},
	queryID string,
	operationName string,
	features map[string]bool,
) (map[string]interface{}, error)

ExecuteGraphQL executes a GraphQL query with variables, queryID, operation name, and features

func (*Client) GetCSRFToken

func (c *Client) GetCSRFToken() string

GetCSRFToken returns the current CSRF token (ct0 cookie value)

func (*Client) OnCSRFRefreshed

func (c *Client) OnCSRFRefreshed(fn func(newToken string))

OnCSRFRefreshed registers a callback invoked whenever the ct0 token is refreshed from a response. Useful for persisting the updated token to a cache or storage.

func (*Client) SetCSRFToken

func (c *Client) SetCSRFToken(token string)

SetCSRFToken sets the CSRF token for requests

func (*Client) SetCookies

func (c *Client) SetCookies(cookies string)

SetCookies sets the cookies for requests

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(httpClient *http.Client)

SetHTTPClient allows you to provide a custom HTTP client.

func (*Client) SetTransactionIDGenerator

func (c *Client) SetTransactionIDGenerator(key string, frames [][][]int)

SetTransactionIDGenerator sets the transaction ID generator with frames and key

func (*Client) UploadMedia

func (c *Client) UploadMedia(filePath string, mediaType string) (string, error)

UploadMedia uploads a media file from a file path and returns the media ID

func (*Client) UploadMediaBytes

func (c *Client) UploadMediaBytes(data []byte, mediaType string) (string, error)

UploadMediaBytes uploads media from a byte slice and returns the media ID

type CreateTweetOptions

type CreateTweetOptions struct {
	MediaIDs      []string      `json:"media_ids,omitempty"`
	MediaEntities []MediaEntity `json:"media_entities,omitempty"`
	ReplyTo       *string       `json:"reply_to,omitempty"`
	Sensitive     bool          `json:"sensitive,omitempty"`
}

CreateTweetOptions contains options for creating a tweet.

type GraphQLRequest

type GraphQLRequest struct {
	Variables map[string]interface{} `json:"variables"`
	QueryID   string                 `json:"queryId"`
	Features  map[string]bool        `json:"features"`
}

GraphQLRequest represents a GraphQL request with variables and features

type ImageInfo

type ImageInfo struct {
	ImageType string `json:"image_type"`
	Width     int    `json:"w"`
	Height    int    `json:"h"`
}

ImageInfo contains image metadata

type MediaEntity

type MediaEntity struct {
	MediaID     string        `json:"media_id"`
	TaggedUsers []interface{} `json:"tagged_users"`
}

MediaEntity represents a media attachment in a tweet

type MediaUploadResponse

type MediaUploadResponse struct {
	MediaID       int64      `json:"media_id"`
	MediaIDString string     `json:"media_id_string"`
	MediaKey      string     `json:"media_key"`
	ExpiresAfter  int        `json:"expires_after_secs"`
	Size          int        `json:"size,omitempty"`
	Image         *ImageInfo `json:"image,omitempty"`
}

MediaUploadResponse represents the response from media upload operations

type PublicMetrics

type PublicMetrics struct {
	RetweetCount  int `json:"retweet_count"`
	ReplyCount    int `json:"reply_count"`
	LikeCount     int `json:"like_count"`
	BookmarkCount int `json:"bookmark_count"`
}

PublicMetrics contains tweet metrics

type ScheduledTweet

type ScheduledTweet struct {
	ID          string    `json:"id"`
	Text        string    `json:"text"`
	ScheduledAt time.Time `json:"scheduled_at"`
}

ScheduledTweet represents a scheduled tweet.

type TransactionIDGenerator

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

TransactionIDGenerator generates X-Client-Transaction-ID headers

func NewTransactionIDGenerator

func NewTransactionIDGenerator(frames [][][]int) *TransactionIDGenerator

NewTransactionIDGenerator creates a new generator with frame data

func (*TransactionIDGenerator) GenerateHeader

func (g *TransactionIDGenerator) GenerateHeader(path, method, key string) string

GenerateHeader generates an X-Client-Transaction-ID header

type Tweet

type Tweet struct {
	ID     string       `json:"rest_id"`
	Legacy *TweetLegacy `json:"legacy"`
}

Tweet represents a Twitter tweet.

type TweetLegacy

type TweetLegacy struct {
	FullText      string         `json:"full_text"`
	CreatedAt     string         `json:"created_at"`
	PublicMetrics *PublicMetrics `json:"public_metrics"`
}

TweetLegacy contains the legacy tweet data

type TweetsService

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

TweetsService handles tweet-related API operations.

func (*TweetsService) Create

func (s *TweetsService) Create(text string, opts *CreateTweetOptions) (*Tweet, error)

Create creates a new tweet.

func (*TweetsService) Delete

func (s *TweetsService) Delete(tweetID string) error

Delete deletes a tweet by ID.

Jump to

Keyboard shortcuts

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