api

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MediaEndpoint is the endpoint for media uploads
	MediaEndpoint = "/2/media/upload"
)

Variables

View Source
var StreamingEndpoints = map[string]bool{
	"/2/tweets/search/stream":           true,
	"/2/tweets/sample/stream":           true,
	"/2/tweets/sample10/stream":         true,
	"/2/tweets/firehose/stream":         true,
	"/2/tweets/firehose/stream/lang/en": true,
	"/2/tweets/firehose/stream/lang/ja": true,
	"/2/tweets/firehose/stream/lang/ko": true,
	"/2/tweets/firehose/stream/lang/pt": true,
}

StreamingEndpoints is a map of endpoint prefixes that should be streamed

Functions

func AddChatConversationKeys added in v1.3.0

func AddChatConversationKeys(client Client, conversationID string, body any, opts RequestOptions) (json.RawMessage, error)

AddChatConversationKeys posts a prepared conversation-key change (initialize or rotate). For a 1:1, conversationID may be the recipient's user id; the server derives the canonical conversation id.

func AddChatGroupMembers added in v1.3.0

func AddChatGroupMembers(client Client, conversationID string, body any, opts RequestOptions) (json.RawMessage, error)

AddChatGroupMembers adds members to a group conversation. body carries the new user_ids plus the rotated key change built from a prepared group members change.

func BlockUser

func BlockUser(client Client, sourceUserID, targetUserID string, opts RequestOptions) (json.RawMessage, error)

BlockUser blocks a user.

func Bookmark

func Bookmark(client Client, userID, postID string, opts RequestOptions) (json.RawMessage, error)

Bookmark bookmarks a post.

func ChatConversationEventID added in v1.3.0

func ChatConversationEventID(id string) string

ChatConversationEventID converts a conversation id to the canonical colon-separated form embedded in events and signatures.

func ChatConversationPathID added in v1.3.0

func ChatConversationPathID(id string) string

ChatConversationPathID converts a conversation id to the form the API URL paths expect (hyphen-separated), from the colon-separated form found inside decrypted events and signatures.

func CompareChatKeyVersions added in v1.3.0

func CompareChatKeyVersions(a, b string) int

CompareChatKeyVersions numerically compares two key version strings (non-padded positive integers, typically millisecond timestamps): -1 when a < b, 0 when equal, 1 when a > b.

func CreatePost

func CreatePost(client Client, text string, mediaIDs []string, opts RequestOptions) (json.RawMessage, error)

CreatePost sends a new post and returns the API response.

func DefaultMediaCategory added in v1.2.0

func DefaultMediaCategory(mediaType string) (string, bool)

DefaultMediaCategory returns the X media_category that matches a MIME type. The boolean is false when the type is not a supported image/video/gif, so the caller can fail clearly instead of forcing an unsupported file into an arbitrary category (which the API would later reject with an opaque error).

func DeletePost

func DeletePost(client Client, postID string, opts RequestOptions) (json.RawMessage, error)

DeletePost deletes a post by ID.

func DetectMediaType added in v1.2.0

func DetectMediaType(filePath string) string

DetectMediaType infers the MIME type from a file's extension, falling back to the system MIME database and finally to a generic binary type.

func DownloadChatMedia added in v1.3.0

func DownloadChatMedia(client Client, conversationID, mediaHashKey string, opts RequestOptions) ([]byte, error)

DownloadChatMedia fetches an encrypted media blob as raw ciphertext bytes. The response is binary, so it bypasses the JSON response path.

func ExecuteMediaStatus

func ExecuteMediaStatus(mediaID, authType, username string, verbose, wait, trace bool, headers []string, client Client) error

ExecuteMediaStatus handles the media status command execution

func ExecuteMediaUpload

func ExecuteMediaUpload(filePath, mediaType, mediaCategory, authType, username string, verbose, waitForProcessing, trace bool, headers []string, client Client) error

ExecuteMediaUpload handles the media upload command execution

func ExecuteRequest

func ExecuteRequest(options RequestOptions, client Client) error

ExecuteRequest handles the execution of a regular API request

func ExecuteStreamRequest

func ExecuteStreamRequest(options RequestOptions, client Client) error

ExecuteStreamRequest handles the execution of a streaming API request

func ExtractCommand

func ExtractCommand(url string) string

extracts command from URL

func ExtractMediaID

func ExtractMediaID(url string) string

ExtractMediaID extracts media_id from URL or data

func ExtractSegmentIndex

func ExtractSegmentIndex(data string) string

ExtractSegmentIndex extracts segment_index from URL or data

func FollowUser

func FollowUser(client Client, sourceUserID, targetUserID string, opts RequestOptions) (json.RawMessage, error)

FollowUser follows a user.

func GetBookmarks

func GetBookmarks(client Client, userID string, maxResults int, opts RequestOptions) (json.RawMessage, error)

GetBookmarks fetches the authenticated user's bookmarks.

func GetChatConversations added in v1.3.0

func GetChatConversations(client Client, maxResults int, paginationToken string, opts RequestOptions) (json.RawMessage, error)

GetChatConversations fetches a page of the authenticated user's chat inbox.

func GetDMEvents

func GetDMEvents(client Client, maxResults int, opts RequestOptions) (json.RawMessage, error)

GetDMEvents fetches recent DM events.

func GetFollowers

func GetFollowers(client Client, userID string, maxResults int, opts RequestOptions) (json.RawMessage, error)

GetFollowers fetches followers of a given user.

func GetFollowing

func GetFollowing(client Client, userID string, maxResults int, opts RequestOptions) (json.RawMessage, error)

GetFollowing fetches users that a given user follows.

func GetLikedPosts

func GetLikedPosts(client Client, userID string, maxResults int, opts RequestOptions) (json.RawMessage, error)

GetLikedPosts fetches posts liked by a user.

func GetMe

func GetMe(client Client, opts RequestOptions) (json.RawMessage, error)

GetMe fetches the authenticated user's profile.

func GetMentions

func GetMentions(client Client, userID string, maxResults int, opts RequestOptions) (json.RawMessage, error)

GetMentions fetches recent mentions for a user.

func GetTimeline

func GetTimeline(client Client, userID string, maxResults int, opts RequestOptions) (json.RawMessage, error)

GetTimeline fetches the authenticated user's reverse‑chronological timeline. Route: GET /2/users/{id}/timelines/reverse_chronological

func GetUserByID added in v1.3.0

func GetUserByID(client Client, userID string, opts RequestOptions) (json.RawMessage, error)

GetUserByID fetches a user object by id (used to render sender usernames).

func GetUserPosts

func GetUserPosts(client Client, userID string, maxResults int, opts RequestOptions) (json.RawMessage, error)

GetUserPosts fetches recent posts by a user ID.

func HandleMediaAppendRequest

func HandleMediaAppendRequest(options RequestOptions, mediaFile string, client Client) (json.RawMessage, error)

HandleMediaAppendRequest handles a media append request with a file

func HandleRequest

func HandleRequest(options RequestOptions, forceStream bool, mediaFile string, client Client) error

HandleRequest determines the type of request and executes it accordingly

func InitializeChatMediaUpload added in v1.3.0

func InitializeChatMediaUpload(client Client, conversationID string, totalBytes int, opts RequestOptions) (sessionID, mediaHashKey string, err error)

InitializeChatMediaUpload starts an encrypted media upload session. totalBytes is the size of the ciphertext, not the plaintext. The media endpoints take the colon form of the conversation id in bodies.

func IsMediaAppendRequest

func IsMediaAppendRequest(url string, mediaFile string) bool

IsMediaAppendRequest checks if the request is a media append request

func IsStreamingEndpoint

func IsStreamingEndpoint(endpoint string) bool

IsStreamingEndpoint checks if an endpoint should be streamed

func LikePost

func LikePost(client Client, userID, postID string, opts RequestOptions) (json.RawMessage, error)

LikePost likes a post on behalf of the authenticated user.

func LookupUser

func LookupUser(client Client, username string, opts RequestOptions) (json.RawMessage, error)

LookupUser fetches a user by username.

func MarkChatRead added in v1.3.0

func MarkChatRead(client Client, conversationID, seenUntilSequenceID string, opts RequestOptions) (json.RawMessage, error)

MarkChatRead marks a conversation read up to the given sequence id.

func MuteUser

func MuteUser(client Client, sourceUserID, targetUserID string, opts RequestOptions) (json.RawMessage, error)

MuteUser mutes a user.

func QuotePost

func QuotePost(client Client, postID, text string, opts RequestOptions) (json.RawMessage, error)

QuotePost sends a quote post.

func ReadPost

func ReadPost(client Client, postID string, opts RequestOptions) (json.RawMessage, error)

ReadPost fetches a single post with useful expansions.

func ReplyToPost

func ReplyToPost(client Client, postID, text string, mediaIDs []string, opts RequestOptions) (json.RawMessage, error)

ReplyToPost sends a reply to an existing post.

func Repost

func Repost(client Client, userID, postID string, opts RequestOptions) (json.RawMessage, error)

Repost reposts a post.

func ResolvePostID

func ResolvePostID(input string) string

ResolvePostID extracts a post ID from a full URL or returns the input as‑is. Accepts:

func ResolveUsername

func ResolveUsername(input string) string

ResolveUsername normalises a username – strips a leading "@" if present.

func SearchPosts

func SearchPosts(client Client, query string, maxResults int, opts RequestOptions) (json.RawMessage, error)

SearchPosts searches recent posts.

func SendChatMessage added in v1.3.0

func SendChatMessage(client Client, conversationID string, body ChatSendBody, opts RequestOptions) (json.RawMessage, error)

SendChatMessage posts an encrypted message produced by chat-xdk.

func SendChatTyping added in v1.3.0

func SendChatTyping(client Client, conversationID string, opts RequestOptions) (json.RawMessage, error)

SendChatTyping sends a typing indicator to a conversation.

func SendDM

func SendDM(client Client, participantID, text string, opts RequestOptions) (json.RawMessage, error)

SendDM sends a direct message to a user.

func UnblockUser

func UnblockUser(client Client, sourceUserID, targetUserID string, opts RequestOptions) (json.RawMessage, error)

UnblockUser unblocks a user.

func Unbookmark

func Unbookmark(client Client, userID, postID string, opts RequestOptions) (json.RawMessage, error)

Unbookmark removes a bookmark.

func UnfollowUser

func UnfollowUser(client Client, sourceUserID, targetUserID string, opts RequestOptions) (json.RawMessage, error)

UnfollowUser unfollows a user.

func UnlikePost

func UnlikePost(client Client, userID, postID string, opts RequestOptions) (json.RawMessage, error)

UnlikePost unlikes a post.

func UnmuteUser

func UnmuteUser(client Client, sourceUserID, targetUserID string, opts RequestOptions) (json.RawMessage, error)

UnmuteUser unmutes a user.

func Unrepost

func Unrepost(client Client, userID, postID string, opts RequestOptions) (json.RawMessage, error)

Unrepost removes a repost.

func UploadChatMedia added in v1.3.0

func UploadChatMedia(client Client, sessionID, conversationID, mediaHashKey string, ciphertext []byte, opts RequestOptions) error

UploadChatMedia appends the ciphertext in 3 MB base64 segments and finalizes the session.

Types

type ApiClient

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

ApiClient handles API requests

func NewApiClient

func NewApiClient(config *config.Config, auth *auth.Auth) *ApiClient

NewApiClient creates a new ApiClient

func (*ApiClient) BuildMultipartRequest

func (c *ApiClient) BuildMultipartRequest(options MultipartOptions) (*http.Request, error)

BuildMultipartRequest builds an HTTP request with multipart form data

func (*ApiClient) BuildRequest

func (c *ApiClient) BuildRequest(requestOptions RequestOptions) (*http.Request, error)

BuildRequest builds an HTTP request

func (*ApiClient) SendMultipartRequest

func (c *ApiClient) SendMultipartRequest(options MultipartOptions) (json.RawMessage, error)

SendMultipartRequest sends an HTTP request with multipart form data

func (*ApiClient) SendRequest

func (c *ApiClient) SendRequest(options RequestOptions) (json.RawMessage, error)

SendRequest sends an HTTP request

func (*ApiClient) StreamRequest

func (c *ApiClient) StreamRequest(options RequestOptions) error

StreamRequest sends an HTTP request and streams the response

type ChatConversationMeta added in v1.3.0

type ChatConversationMeta struct {
	ParticipantIDs               []string `json:"participant_ids"`
	MemberIDs                    []string `json:"member_ids"`
	AdminIDs                     []string `json:"admin_ids"`
	GroupName                    string   `json:"group_name"`
	GroupAvatarURL               string   `json:"group_avatar_url"`
	MessageTTLMs                 *int64   `json:"message_ttl_ms"`
	ScreenCaptureBlockingEnabled *bool    `json:"screen_capture_blocking_enabled"`
}

ChatConversationMeta is a conversation's metadata. Group name and avatar URL arrive encrypted under the conversation key when the group set them from an encrypted client.

func GetChatConversation added in v1.3.0

func GetChatConversation(client Client, conversationID string, opts RequestOptions) (*ChatConversationMeta, json.RawMessage, error)

GetChatConversation fetches one conversation's metadata.

func (*ChatConversationMeta) AllUserIDs added in v1.3.0

func (m *ChatConversationMeta) AllUserIDs() []string

AllUserIDs returns the deduplicated union of participant, member, and admin ids.

type ChatEventItem added in v1.3.0

type ChatEventItem struct {
	ID             string `json:"id"`
	ConversationID string `json:"conversation_id"`
	SenderID       string `json:"sender_id"`
	EncodedEvent   string `json:"encoded_event"`
	IsTrusted      bool   `json:"is_trusted"`
}

ChatEventItem is one element of the conversation events response. ID is the event's sequence id (the resource exposes sequence_id as id).

type ChatEventsPage added in v1.3.0

type ChatEventsPage struct {
	Events []ChatEventItem
	// KeyEvents are base64-encoded key-change events that apply to messages
	// in this page but are not part of it (meta.conversation_key_events).
	// Feed them to the SDK's batch decrypt alongside the page's events so
	// the conversation keys can be extracted.
	KeyEvents []string
	NextToken string
}

ChatEventsPage is one page of a conversation's events.

func GetChatEvents added in v1.3.0

func GetChatEvents(client Client, conversationID string, maxResults int, paginationToken string, opts RequestOptions) (*ChatEventsPage, error)

GetChatEvents fetches a page of raw (encrypted) events for a conversation.

type ChatPublicKey added in v1.3.0

type ChatPublicKey struct {
	// UserID tags the key's owner; only the batch endpoint
	// (GET /2/users/public_keys) sets it.
	UserID                     string          `json:"user_id,omitempty"`
	Version                    string          `json:"public_key_version"`
	PublicKey                  string          `json:"public_key"`
	SigningPublicKey           string          `json:"signing_public_key"`
	IdentityPublicKeySignature string          `json:"identity_public_key_signature"`
	JuiceboxConfig             json.RawMessage `json:"juicebox_config,omitempty"`
}

ChatPublicKey is one registered public key row for a user. Every field of the public_key resource is always included by the API (no public_key.fields parameter exists for opting in); the version field is exposed as public_key_version.

func GetChatPublicKeys added in v1.3.0

func GetChatPublicKeys(client Client, userID string, opts RequestOptions) ([]ChatPublicKey, error)

GetChatPublicKeys fetches a user's registered public keys (including the juicebox_config, which the API always returns).

func GetChatUsersPublicKeys added in v1.3.0

func GetChatUsersPublicKeys(client Client, userIDs []string, opts RequestOptions) ([]ChatPublicKey, error)

GetChatUsersPublicKeys fetches registered public keys for the given users; each returned row carries its owner's user_id. The endpoint accepts at most 100 ids per request, so larger inputs are fetched in batches.

type ChatSendBody added in v1.3.0

type ChatSendBody struct {
	MessageID                    string `json:"message_id"`
	EncodedMessageCreateEvent    string `json:"encoded_message_create_event"`
	EncodedMessageEventSignature string `json:"encoded_message_event_signature"`
	ConversationToken            string `json:"conversation_token,omitempty"`
}

ChatSendBody is the request body for sending an encrypted chat message.

type Client

type Client interface {
	BuildRequest(requestOptions RequestOptions) (*http.Request, error)
	BuildMultipartRequest(options MultipartOptions) (*http.Request, error)
	SendRequest(options RequestOptions) (json.RawMessage, error)
	StreamRequest(options RequestOptions) error
	SendMultipartRequest(options MultipartOptions) (json.RawMessage, error)
}

Client is an interface for API clients

type InitRequest

type InitRequest struct {
	TotalBytes    int64  `json:"total_bytes"`
	MediaType     string `json:"media_type"`
	MediaCategory string `json:"media_category"`
}

type MediaUploader

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

MediaUploader handles media upload operations

func NewMediaUploader

func NewMediaUploader(client Client, filePath string, verbose, trace bool, authType string, username string, headers []string) (*MediaUploader, error)

NewMediaUploader creates a new MediaUploader

func NewMediaUploaderWithoutFile

func NewMediaUploaderWithoutFile(client Client, verbose, trace bool, authType string, username string, headers []string) *MediaUploader

func (*MediaUploader) Append

func (m *MediaUploader) Append() error

Append uploads the media in chunks

func (*MediaUploader) CheckStatus

func (m *MediaUploader) CheckStatus() (json.RawMessage, error)

CheckStatus checks the status of the media upload

func (*MediaUploader) Finalize

func (m *MediaUploader) Finalize() (json.RawMessage, error)

Finalize finalizes the media upload

func (*MediaUploader) GetMediaID

func (m *MediaUploader) GetMediaID() string

GetMediaID returns the media ID

func (*MediaUploader) Init

func (m *MediaUploader) Init(mediaType string, mediaCategory string) error

Init initializes the media upload

func (*MediaUploader) SetMediaID

func (m *MediaUploader) SetMediaID(mediaID string)

SetMediaID sets the media ID

func (*MediaUploader) WaitForProcessing

func (m *MediaUploader) WaitForProcessing() (json.RawMessage, error)

WaitForProcessing waits for media processing to complete

type MultipartOptions

type MultipartOptions struct {
	RequestOptions
	FormFields map[string]string
	FileField  string
	FilePath   string
	FileName   string
	FileData   []byte
}

MultipartOptions contains options specific to multipart requests

type PostBody

type PostBody struct {
	Text  string     `json:"text"`
	Reply *PostReply `json:"reply,omitempty"`
	Quote *string    `json:"quote_tweet_id,omitempty"` // API field name — do not rename
	Media *PostMedia `json:"media,omitempty"`
	Poll  *PostPoll  `json:"poll,omitempty"`
}

PostBody is the JSON body for POST /2/tweets

type PostMedia

type PostMedia struct {
	MediaIDs []string `json:"media_ids"`
}

PostMedia nests inside PostBody to attach uploaded media

type PostPoll

type PostPoll struct {
	Options         []string `json:"options"`
	DurationMinutes int      `json:"duration_minutes"`
}

PostPoll nests inside PostBody to create a poll

type PostReply

type PostReply struct {
	InReplyToPostID string `json:"in_reply_to_tweet_id"` // API field name — do not rename
}

PostReply nests inside PostBody for replies

type RequestOptions

type RequestOptions struct {
	Method   string
	Endpoint string
	Headers  []string
	Data     string
	AuthType string
	Username string
	Verbose  bool
	Trace    bool
}

RequestOptions contains common options for API requests

Jump to

Keyboard shortcuts

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