Documentation
¶
Overview ¶
Package instagram provides a Go client for Instagram's private web/mobile API.
It supports authenticated profile lookup, post and reel feeds, comments, followers/following, stories, hashtags, locations, search, narrowly scoped account administration, and explicitly confirmed plain-text Instagram Direct messaging — giving programmatic access to Instagram's content graph and safe reversible settings from a logged-in browser session. It also defines a bounded, fail-closed publishing draft that remains disabled until a reviewed live burner capture is compiled in.
Zero production dependencies — stdlib only.
Authentication ¶
Required cookies (obtained from a browser export of an authenticated session):
- sessionid primary session credential
- csrftoken CSRF token (also sent as X-CSRFToken header)
- ds_user_id numeric user ID of the logged-in account
- datr device auth token
- mid machine ID
- ig_did device ID (recommended)
User-Agent ¶
Instagram's API rejects desktop browser user-agents with {"message": "useragent mismatch"}. The default UA is the Instagram Android app's UA string. Override via WithUserAgent only if you have a known-good alternative.
Rate limiting ¶
Instagram does not return X-RateLimit headers. The client paces requests with a leaky-bucket minimum gap (default 4s) and exponential backoff on HTTP 429 / "Please wait a few minutes" responses.
Write actions (Follow, Unfollow, Like, Comment, etc.) are subject to a stricter, separate rate limiter than reads. The client enforces a longer minimum gap (default 12s) between writes and applies aggressive backoff on any 302-to-login response, which Instagram uses to indicate a write soft block. Account-administration writes additionally require an expected account ID, explicit before/after values, and confirmation; ambiguous writes are not retried.
Index ¶
- Constants
- Variables
- type APIError
- type AccountMismatchError
- type AccountMutationResult
- type AccountSearchResult
- type AccountSettings
- type AudioInfo
- type Client
- func (c *Client) Block(ctx context.Context, userID string) (*FriendshipStatus, error)
- func (c *Client) DeleteComment(ctx context.Context, mediaPK, commentID string) error
- func (c *Client) DeleteMedia(ctx context.Context, mediaID string, kind PublishedMediaKind) error
- func (c *Client) Follow(ctx context.Context, userID string) (*FriendshipStatus, error)
- func (c *Client) FollowHashtag(ctx context.Context, name string) error
- func (c *Client) GetAccountSettings(ctx context.Context) (*AccountSettings, error)
- func (c *Client) GetCommentLikers(ctx context.Context, mediaPK, commentID string) ([]*User, error)
- func (c *Client) GetCommentReplies(mediaPK, parentID string) *Iterator[*Comment]
- func (c *Client) GetComments(mediaPK string) *Iterator[*Comment]
- func (c *Client) GetCurrentAccount(ctx context.Context) (*CurrentAccount, error)
- func (c *Client) GetDirectInbox() *Iterator[*DirectThread]
- func (c *Client) GetDirectThread(threadID string) *Iterator[*DirectItem]
- func (c *Client) GetExplore() *Iterator[*Post]
- func (c *Client) GetFollowers(userID string) *Iterator[*User]
- func (c *Client) GetFollowing(userID string) *Iterator[*User]
- func (c *Client) GetFriendship(ctx context.Context, userID string) (*FriendshipStatus, error)
- func (c *Client) GetFriendships(ctx context.Context, userIDs []string) (map[string]*FriendshipStatus, error)
- func (c *Client) GetHashtag(ctx context.Context, name string) (*Hashtag, error)
- func (c *Client) GetHashtagClips(name string) *Iterator[*Post]
- func (c *Client) GetHashtagPosts(name string) *Iterator[*Post]
- func (c *Client) GetHashtagTopPosts(name string) *Iterator[*Post]
- func (c *Client) GetHighlights(ctx context.Context, userID string) ([]*StoryReel, error)
- func (c *Client) GetLikers(ctx context.Context, mediaPK string) ([]*User, error)
- func (c *Client) GetLocation(ctx context.Context, id string) (*Location, error)
- func (c *Client) GetLocationPosts(id string) *Iterator[*Post]
- func (c *Client) GetLocationTopPosts(id string) *Iterator[*Post]
- func (c *Client) GetPost(ctx context.Context, shortcode string) (*Post, error)
- func (c *Client) GetPostByID(ctx context.Context, mediaID string) (*Post, error)
- func (c *Client) GetPosts(userID string) *Iterator[*Post]
- func (c *Client) GetProfessionalAccountState(ctx context.Context) (*ProfessionalAccountState, error)
- func (c *Client) GetProfile(ctx context.Context, username string) (*User, error)
- func (c *Client) GetProfileByID(ctx context.Context, userID string) (*User, error)
- func (c *Client) GetReels(userID string) *Iterator[*Post]
- func (c *Client) GetReelsMedia(ctx context.Context, reelIDs []string) (map[string]*StoryReel, error)
- func (c *Client) GetStoryTray(ctx context.Context) ([]*StoryReel, error)
- func (c *Client) GetSuggestedUsers(ctx context.Context, targetID string) ([]*User, error)
- func (c *Client) GetTaggedPosts(userID string) *Iterator[*Post]
- func (c *Client) GetTimeline() *Iterator[*Post]
- func (c *Client) GetUserStories(ctx context.Context, userID string) (*StoryReel, error)
- func (c *Client) KeywordTypeahead(ctx context.Context, query string) ([]string, error)
- func (c *Client) LikeComment(ctx context.Context, commentID string) error
- func (c *Client) LikePost(ctx context.Context, mediaPK string) error
- func (c *Client) MarkStorySeen(ctx context.Context, reelID, mediaPK string, takenAt int64) error
- func (c *Client) Me(ctx context.Context) (*User, error)
- func (c *Client) MutePosts(ctx context.Context, userID string) error
- func (c *Client) PostComment(ctx context.Context, mediaPK, text string) (*Comment, error)
- func (c *Client) PublishPhoto(ctx context.Context, in PublishPhotoInput) (*PublishResult, error)
- func (c *Client) PublishReel(ctx context.Context, in PublishReelInput) (*PublishResult, error)
- func (c *Client) PublishStory(ctx context.Context, in PublishStoryInput) (*PublishResult, error)
- func (c *Client) RateLimit() RateLimitState
- func (c *Client) SavePost(ctx context.Context, mediaPK string) error
- func (c *Client) Search(ctx context.Context, query string) (*SearchResult, error)
- func (c *Client) SearchAccounts(ctx context.Context, query string) (*AccountSearchResult, error)
- func (c *Client) SearchKeywordPosts(query string) *Iterator[*Post]
- func (c *Client) SearchLocations(ctx context.Context, query string) ([]*Location, error)
- func (c *Client) SearchPosts(query string) *Iterator[*Post]
- func (c *Client) SearchReels(query string) *Iterator[*Post]
- func (c *Client) SearchTypeaheadUsers(ctx context.Context, query string, count int) (*TypeaheadSearchResult, error)
- func (c *Client) SearchUsers(ctx context.Context, query string, count int) ([]*User, error)
- func (c *Client) SendDirectText(ctx context.Context, in DirectTextRequest) (*DirectSendResult, error)
- func (c *Client) SetPrivacy(ctx context.Context, p SetPrivacyParams) (*AccountMutationResult[bool], error)
- func (c *Client) Unblock(ctx context.Context, userID string) (*FriendshipStatus, error)
- func (c *Client) Unfollow(ctx context.Context, userID string) (*FriendshipStatus, error)
- func (c *Client) UnfollowHashtag(ctx context.Context, name string) error
- func (c *Client) UnlikeComment(ctx context.Context, commentID string) error
- func (c *Client) UnlikePost(ctx context.Context, mediaPK string) error
- func (c *Client) UnmutePosts(ctx context.Context, userID string) error
- func (c *Client) UnsavePost(ctx context.Context, mediaPK string) error
- func (c *Client) UpdateProfessionalSettings(ctx context.Context, p UpdateProfessionalSettingsParams) (*AccountMutationResult[ProfessionalSettings], error)
- func (c *Client) UpdateProfileFields(ctx context.Context, p UpdateProfileFieldsParams) (*AccountMutationResult[ProfileFields], error)
- func (c *Client) WaitForCooldown(ctx context.Context) error
- type ClipsMetadata
- type Comment
- type Cookies
- type CurrentAccount
- type DirectItem
- type DirectSendError
- type DirectSendResult
- type DirectTextRequest
- type DirectThread
- type FriendshipStatus
- type Hashtag
- type ImageVersion
- type Iterator
- func (it *Iterator[T]) Collect(ctx context.Context) ([]T, error)
- func (it *Iterator[T]) Cursor() string
- func (it *Iterator[T]) Err() error
- func (it *Iterator[T]) Item() T
- func (it *Iterator[T]) Next(ctx context.Context) bool
- func (it *Iterator[T]) WithCursor(cursor string) *Iterator[T]
- func (it *Iterator[T]) WithMaxPages(n int) *Iterator[T]
- type Location
- type LoginParams
- type LoginResult
- type MediaType
- type MutationPreconditionError
- type Option
- func WithAPIAppID(id string) Option
- func WithAPIHost(host string) Option
- func WithAPIUserAgent(ua string) Option
- func WithAppID(id string) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithMinRequestGap(d time.Duration) Option
- func WithMinWriteGap(d time.Duration) Option
- func WithProxy(proxyURL string) Option
- func WithPublishingLimits(photoBytes, videoBytes int64) Option
- func WithPublishingTimeouts(upload, processing time.Duration) Option
- func WithRateLimitCooldown(read, write time.Duration) Option
- func WithRetry(maxAttempts int, base time.Duration) Option
- func WithSkipSessionValidation() Option
- func WithUserAgent(ua string) Option
- func WithWWWHost(host string) Option
- type Page
- type PageOptions
- type Place
- type Post
- type ProfessionalAccountState
- type ProfessionalSettings
- type ProfileFields
- type PublishError
- type PublishPhotoInput
- type PublishReelInput
- type PublishResult
- type PublishStoryInput
- type PublishedMediaKind
- type RateLimitState
- type SearchResult
- type SetPrivacyParams
- type Story
- type StoryReel
- type TypeaheadSearchResult
- type UpdateProfessionalSettingsParams
- type UpdateProfileFieldsParams
- type UploadSource
- type User
- type VideoVersion
Constants ¶
const PublishingCaptureVersion = ""
PublishingCaptureVersion identifies the reviewed live burner capture compiled into the SDK. It intentionally remains empty while the repository contains only draft/offline fixtures: all publishing methods fail closed before consuming a stream or making an HTTP request. A future implementation may set this only in the same change that commits the reviewed, date-stamped capture.
Variables ¶
var ( // ErrInvalidAuth indicates missing or malformed cookies, or that // validateSession could not fetch the current user. ErrInvalidAuth = errors.New("instagram: invalid auth") // ErrSessionExpired is returned when Instagram redirects to /accounts/login/ // or wipes the sessionid cookie, indicating the session is no longer valid. ErrSessionExpired = errors.New("instagram: session expired or invalidated") // ErrRateLimited is returned when Instagram throttles the request. // On reads this is a 429 or "Please wait a few minutes" body. // On writes it is most often a 302 redirect to the login page. ErrRateLimited = errors.New("instagram: rate limited") // ErrWriteSoftBlock is returned when a write action is rejected with a // 302-to-login that does not invalidate the read session. Try again later // or from a different IP / device. ErrWriteSoftBlock = errors.New("instagram: write soft-blocked") // ErrChallengeRequired is returned when Instagram requires the account to // complete a security challenge (checkpoint) before continuing. ErrChallengeRequired = errors.New("instagram: checkpoint / challenge required") // ErrFeedbackRequired is returned when Instagram rejects publishing with // feedback_required. It is also classified as ErrWriteSoftBlock so existing // callers that only understand the broader write classification keep working. ErrFeedbackRequired = errors.New("instagram: feedback required") // ErrProcessingFailed is returned when Instagram accepts an upload but its // asynchronous media processor reaches a terminal failure state. ErrProcessingFailed = errors.New("instagram: media processing failed") // ErrProcessingTimeout is returned when an uploaded media item does not // reach a captured terminal processing state before the processing deadline. ErrProcessingTimeout = errors.New("instagram: media processing timed out") // ErrPartialUpload is returned after Instagram may have accepted upload // bytes but a later upload/configure/status stage failed. Callers must not // blindly retry with a different idempotency key. ErrPartialUpload = errors.New("instagram: partial upload") // ErrUploadTooLarge is returned locally, before any request, when declared // or streamed media exceeds the configured upload limit. ErrUploadTooLarge = errors.New("instagram: upload too large") // ErrInvalidPublishInput is returned locally, before any request, when // publishing metadata, MIME type, dimensions, duration, or stream length is // invalid. ErrInvalidPublishInput = errors.New("instagram: invalid publishing input") // ErrPublishingCaptureRequired is returned before consuming media or making // an HTTP request while no reviewed, current burner capture is compiled into // the SDK. Publishing deliberately fails closed until that evidence exists. ErrPublishingCaptureRequired = errors.New("instagram: verified publishing capture required") // ErrNotFound is returned for 404s and for usernames/IDs that resolve to // a user_not_found response from Instagram. ErrNotFound = errors.New("instagram: not found") // ErrPrivateAccount is returned when the requested resource belongs to a // private account that the authenticated user does not follow. ErrPrivateAccount = errors.New("instagram: private account") ErrMediaUnavailable = errors.New("instagram: media unavailable") // ErrCSRF is returned when Instagram rejects a write with a CSRF error. ErrCSRF = errors.New("instagram: csrf token rejected") // ErrAccountMismatch is returned when an authenticated account response or // mutation target does not match the ds_user_id bound to this client. ErrAccountMismatch = errors.New("instagram: authenticated account mismatch") // ErrMutationPrecondition is returned when an account administration write // is unconfirmed, is a no-op, or its explicit Before value is stale. ErrMutationPrecondition = errors.New("instagram: mutation precondition failed") // ErrUnexpectedResponse is returned when the response is well-formed but // does not contain the expected fields. The wrapped error gives detail. ErrUnexpectedResponse = errors.New("instagram: unexpected response") )
Sentinel errors. Use errors.Is for matching.
Functions ¶
This section is empty.
Types ¶
type AccountMismatchError ¶ added in v1.4.0
AccountMismatchError identifies the expected and observed account IDs without exposing credentials or response bodies.
func (*AccountMismatchError) Error ¶ added in v1.4.0
func (e *AccountMismatchError) Error() string
func (*AccountMismatchError) Unwrap ¶ added in v1.4.0
func (e *AccountMismatchError) Unwrap() error
type AccountMutationResult ¶ added in v1.4.0
type AccountMutationResult[T any] struct { AccountID string `json:"account_id"` Before T `json:"before"` After T `json:"after"` Verified bool `json:"verified"` }
AccountMutationResult records the verified state transition.
type AccountSearchResult ¶ added in v1.4.0
type AccountSearchResult struct {
Users []*User `json:"users"`
NumResults int `json:"num_results"`
HasMore bool `json:"has_more"`
PageToken string `json:"page_token,omitempty"`
RankToken string `json:"rank_token,omitempty"`
}
AccountSearchResult is one typed page from the mobile account SERP. PageToken and RankToken are returned for observability; continuation request parameters were not proven by the inventory and are intentionally not sent.
type AccountSettings ¶ added in v1.4.0
type AccountSettings struct {
AccountID string `json:"account_id"`
Profile ProfileFields `json:"profile"`
IsPrivate bool `json:"is_private"`
}
AccountSettings contains the reversible settings approved for mutation.
type AudioInfo ¶
type AudioInfo struct {
AudioAssetID string `json:"audio_asset_id,omitempty"`
OriginalAudio bool `json:"original_audio,omitempty"`
ArtistName string `json:"display_artist,omitempty"`
Title string `json:"title,omitempty"`
DurationMs int64 `json:"duration_in_ms,omitempty"`
OwnerID string `json:"original_media_id,omitempty"`
ProgressiveURL string `json:"progressive_download_url,omitempty"`
IPADURL string `json:"dash_manifest,omitempty"`
}
AudioInfo describes the audio track used in a reel.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an Instagram API client. It is safe for concurrent use.
func New ¶
New creates a Client and validates the session by fetching the current user. Returns ErrInvalidAuth if SessionID, CSRFToken, or DSUserID are empty.
func (*Client) Block ¶
Block blocks a user.
Endpoint: POST /api/v1/friendships/block/<user_id>/
Note: this and the other tier-2 friendship writes (Mute, SetBesties) are often soft-blocked on web sessions. See ErrWriteSoftBlock.
func (*Client) DeleteComment ¶
DeleteComment deletes a comment authored by the viewer (or on the viewer's post).
Endpoint: POST /api/v1/media/<media_pk>/comment/<comment_id>/delete/
func (*Client) DeleteMedia ¶ added in v1.4.0
DeleteMedia deletes exactly one caller-supplied media ID using the per-kind deletion discriminator established by the reviewed capture. It exists for burner verification cleanup and deliberately does not enumerate account data.
func (*Client) FollowHashtag ¶
FollowHashtag starts following a hashtag.
Endpoint: POST /api/v1/web/tags/follow/<name>/
Note: subject to write rate-limiting; see ErrWriteSoftBlock.
func (*Client) GetAccountSettings ¶ added in v1.4.0
func (c *Client) GetAccountSettings(ctx context.Context) (*AccountSettings, error)
GetAccountSettings fetches only the reversible profile and privacy fields.
func (*Client) GetCommentLikers ¶
GetCommentLikers fetches the users who liked a specific comment on a post.
Endpoint: GET /api/v1/media/<media_pk>/comment_likers/?comment_id=<id>
func (*Client) GetCommentReplies ¶
GetCommentReplies iterates over the child replies under a parent comment.
Endpoint: GET /api/v1/media/<media_pk>/comments/<parent_id>/child_comments/
func (*Client) GetComments ¶
GetComments iterates over the top-level comments on a post.
mediaPK is the numeric pk of the post (Post.PK or Post.ID up to '_').
Endpoint: GET /api/v1/media/<media_pk>/comments/
func (*Client) GetCurrentAccount ¶ added in v1.4.0
func (c *Client) GetCurrentAccount(ctx context.Context) (*CurrentAccount, error)
GetCurrentAccount fetches the authenticated account's safe identity and editable profile projection.
func (*Client) GetDirectInbox ¶ added in v1.4.0
func (c *Client) GetDirectInbox() *Iterator[*DirectThread]
GetDirectInbox iterates over threads in the authenticated viewer's primary Direct inbox. Cursor values are versioned and opaque.
Endpoint: GET i.instagram.com/api/v1/direct_v2/inbox/
func (*Client) GetDirectThread ¶ added in v1.4.0
func (c *Client) GetDirectThread(threadID string) *Iterator[*DirectItem]
GetDirectThread iterates over items in a selected Direct thread. Cursors are bound to threadID so a cursor cannot be replayed against another conversation.
Endpoint: GET i.instagram.com/api/v1/direct_v2/threads/<thread_id>/
func (*Client) GetExplore ¶
GetExplore fetches the Explore feed.
Endpoint: GET /api/v1/discover/topical_explore/
func (*Client) GetFollowers ¶
GetFollowers iterates over a user's followers.
Endpoint: GET /api/v1/friendships/<user_id>/followers/?count=12&max_id=<cursor>
Note: pagination is best-effort. Instagram caps deep follower lists for large accounts, and very high page indices are silently truncated.
func (*Client) GetFollowing ¶
GetFollowing iterates over the accounts a user is following.
Endpoint: GET /api/v1/friendships/<user_id>/following/
func (*Client) GetFriendship ¶
GetFriendship returns the viewer's relationship with one user.
Endpoint: GET /api/v1/friendships/show/<user_id>/
func (*Client) GetFriendships ¶
func (c *Client) GetFriendships(ctx context.Context, userIDs []string) (map[string]*FriendshipStatus, error)
GetFriendships returns relationship status with many users in one call.
Endpoint: POST /api/v1/friendships/show_many/ with form: user_ids=1,2,3
func (*Client) GetHashtag ¶
GetHashtag fetches the metadata for a hashtag.
Endpoint: GET /api/v1/tags/web_info/?tag_name=<name>
func (*Client) GetHashtagClips ¶
GetHashtagClips iterates over reels (clips) under a hashtag.
Endpoint: GET /api/v1/tags/<tag>/sections/?tab=clips
func (*Client) GetHashtagPosts ¶
GetHashtagPosts iterates over the recent posts under a hashtag.
Endpoint: GET /api/v1/tags/<tag>/sections/?tab=recent
func (*Client) GetHashtagTopPosts ¶
GetHashtagTopPosts iterates over the top (algorithmically ranked) posts under a hashtag.
Endpoint: GET /api/v1/tags/<tag>/sections/?tab=top
func (*Client) GetHighlights ¶
GetHighlights fetches a user's saved story highlight reels.
Endpoint: GET /api/v1/highlights/<user_id>/highlights_tray/
func (*Client) GetLikers ¶
GetLikers fetches the users who liked a post.
Endpoint: GET /api/v1/media/<media_pk>/likers/
Note: this is a one-shot endpoint — Instagram does not paginate likers. For posts with very many likes, only the first ~1000 are returned.
func (*Client) GetLocation ¶
GetLocation fetches the metadata for a location by its numeric ID.
Endpoint: GET /api/v1/locations/<id>/info/
func (*Client) GetLocationPosts ¶
GetLocationPosts iterates over the recent posts at a location.
Endpoint: GET /api/v1/locations/<id>/sections/?tab=recent
func (*Client) GetLocationTopPosts ¶
GetLocationTopPosts iterates over the top posts at a location.
Endpoint: GET /api/v1/locations/<id>/sections/?tab=ranked
func (*Client) GetPost ¶
GetPost fetches a single post by its shortcode (the bit between /p/ and / in the public URL, e.g. "DXHKcyvEWfr").
Internally the shortcode is decoded to a numeric media ID via the standard Instagram base64 alphabet, then GET /api/v1/media/{media_id}/info/ is hit.
To fetch by numeric ID directly, use GetPostByID.
func (*Client) GetPostByID ¶
GetPostByID fetches a single post by its numeric media ID (Post.PK).
Endpoint: GET /api/v1/media/<media_id>/info/
func (*Client) GetPosts ¶
GetPosts iterates over the timeline posts of a user (most recent first).
Endpoint: GET /api/v1/feed/user/<user_id>/?count=12&max_id=<cursor>
The user_id can be obtained from GetProfile(username).ID.
func (*Client) GetProfessionalAccountState ¶ added in v1.4.0
func (c *Client) GetProfessionalAccountState(ctx context.Context) (*ProfessionalAccountState, error)
GetProfessionalAccountState fetches professional type and display settings.
func (*Client) GetProfile ¶
GetProfile fetches a user's full profile by username.
Endpoint: GET /api/v1/users/web_profile_info/?username=<username>
func (*Client) GetProfileByID ¶
GetProfileByID fetches a user's full profile by their numeric ID.
Endpoint: GET /api/v1/users/<user_id>/info/
func (*Client) GetReels ¶
GetReels iterates over the reels (clips) authored by a user.
Endpoint: POST /api/v1/clips/user/ with form body {target_user_id, max_id, page_size}
func (*Client) GetReelsMedia ¶
func (c *Client) GetReelsMedia(ctx context.Context, reelIDs []string) (map[string]*StoryReel, error)
GetReelsMedia fetches the media items for one or more story reels.
reelIDs are user IDs for live reels, or "highlight:<id>" for highlights.
Endpoint: POST /api/v1/feed/reels_media/
func (*Client) GetStoryTray ¶
GetStoryTray fetches the viewer's story tray (the row of profile circles at the top of the home feed).
Endpoint: GET /api/v1/feed/reels_tray/
func (*Client) GetSuggestedUsers ¶
GetSuggestedUsers returns up to ~80 accounts Instagram suggests based on the given seed user (typically the logged-in user's ID for "Suggested for you", but any user ID works to get accounts related to that user).
Endpoint: GET /api/v1/discover/chaining/?target_id=<user_id>
func (*Client) GetTaggedPosts ¶
GetTaggedPosts iterates over posts the user has been tagged in.
Endpoint: GET /api/v1/usertags/<user_id>/feed/
func (*Client) GetTimeline ¶
GetTimeline fetches the home timeline feed (Following + recommendations).
Endpoint: POST /api/v1/feed/timeline/
func (*Client) GetUserStories ¶
GetUserStories fetches a single user's current story.
Endpoint: GET /api/v1/feed/user/<user_id>/story/
Returns nil if the user has no story.
func (*Client) KeywordTypeahead ¶ added in v1.4.0
KeywordTypeahead returns lightweight suggestion strings for a partial keyword without loading a full search-results page. The inventory-proven typeahead stream currently returns account entities, so suggestions are their usernames (falling back to display names when necessary). Instagram may validly return an empty slice when it has no suggestions.
func (*Client) LikeComment ¶
LikeComment likes a comment.
Endpoint: POST /api/v1/media/<comment_id>/comment_like/
func (*Client) MarkStorySeen ¶
MarkStorySeen marks a story media item as seen by the viewer.
Endpoint: POST /api/v2/media/seen/ with form: reels[<reel_id>][]=<media_pk>_<reel_id>_<taken_at>
Note: subject to write rate-limiting; see ErrWriteSoftBlock.
func (*Client) Me ¶
Me returns the authenticated user's profile. The result is cached at New() time; subsequent calls return the cached value.
func (*Client) MutePosts ¶
MutePosts mutes the posts of a user without unfollowing.
Endpoint: POST /api/v1/friendships/mute_posts_or_story_from_follow/
func (*Client) PostComment ¶
PostComment leaves a top-level comment on a post.
Endpoint: POST /api/v1/media/<media_pk>/comment/
Subject to write rate-limiting; Instagram is aggressive about silent soft-blocks here. See ErrWriteSoftBlock.
func (*Client) PublishPhoto ¶ added in v1.4.0
func (c *Client) PublishPhoto(ctx context.Context, in PublishPhotoInput) (*PublishResult, error)
PublishPhoto uploads and configures one feed photo.
func (*Client) PublishReel ¶ added in v1.4.0
func (c *Client) PublishReel(ctx context.Context, in PublishReelInput) (*PublishResult, error)
PublishReel uploads a video and its thumbnail, waits for captured media processing states, and configures one Reel.
func (*Client) PublishStory ¶ added in v1.4.0
func (c *Client) PublishStory(ctx context.Context, in PublishStoryInput) (*PublishResult, error)
PublishStory publishes one video Story using the captured thumbnail and processing/status contracts before configure.
func (*Client) RateLimit ¶
func (c *Client) RateLimit() RateLimitState
RateLimit returns the most recent rate-limit observation.
func (*Client) SavePost ¶
SavePost saves a post to the user's collection.
Endpoint: POST /api/v1/media/<media_pk>/save/
func (*Client) Search ¶
Search runs a topsearch across users, hashtags, and places.
Endpoint: GET /api/v1/web/search/topsearch/?context=blended&query=<q>
func (*Client) SearchAccounts ¶ added in v1.4.0
SearchAccounts searches the inventory-proven mobile account SERP and returns richer account card context than SearchUsers.
func (*Client) SearchKeywordPosts ¶ added in v1.4.0
SearchKeywordPosts iterates over posts from the authenticated web keyword search GraphQL connection. It uses the inventory-proven initial persisted operation for the first request and the distinct pagination operation for subsequent pages. Cursor returns an opaque, query-bound continuation value containing the Relay cursor and both search session IDs, so it can be passed to WithCursor on a fresh iterator without changing the search session.
Persisted document IDs are private, dated contracts and can rotate. A stale or malformed GraphQL response returns ErrUnexpectedResponse.
func (*Client) SearchLocations ¶
SearchLocations searches Instagram's location index by free-text query.
Endpoint: GET /api/v1/location_search/?search_query=<q>
func (*Client) SearchPosts ¶ added in v1.4.0
SearchPosts iterates over posts matching a free-text keyword from Instagram's mobile Top SERP. Results are ranked and personalized by Instagram; callers should deduplicate durable watches by Post.PK.
Endpoint: GET /api/v1/fbsearch/top_serp/
Cursor returns an opaque, query-bound continuation value containing all of the Top SERP pagination state. Pass it to WithCursor on a fresh iterator to resume the same normalized query.
func (*Client) SearchReels ¶ added in v1.4.0
SearchReels returns the first inventory-proven mobile Reels SERP as an iterator of Post values. The captured endpoint exposes a continuation token, but the corresponding request parameter has not been proven, so the iterator deliberately makes at most one upstream request and rejects cursors locally.
func (*Client) SearchTypeaheadUsers ¶ added in v1.4.0
func (c *Client) SearchTypeaheadUsers(ctx context.Context, query string, count int) (*TypeaheadSearchResult, error)
SearchTypeaheadUsers fetches account suggestions from the inventory-proven mobile keyword typeahead stream. Pass count <= 0 to use the captured value of 30.
func (*Client) SearchUsers ¶
SearchUsers searches Instagram for users matching a query.
Endpoint: GET /api/v1/users/search/?q=<query>&count=<n>
count clamps to 50 server-side; pass 0 to use the default (~12).
func (*Client) SendDirectText ¶ added in v1.4.0
func (c *Client) SendDirectText(ctx context.Context, in DirectTextRequest) (*DirectSendResult, error)
SendDirectText creates/resolves a one-recipient thread and broadcasts a plain-text item. The entire mutation is capped at 30 seconds. Thread creation is never automatically retried; broadcast retries reuse the same client context, mutation token, and offline threading ID. To retry an uncertain broadcast without repeating non-idempotent thread creation, pass the ThreadID, ClientContext, and RetryToken from DirectSendError. The authenticated token binds those values to the original recipient and text.
func (*Client) SetPrivacy ¶ added in v1.4.0
func (c *Client) SetPrivacy(ctx context.Context, p SetPrivacyParams) (*AccountMutationResult[bool], error)
SetPrivacy changes only the account's public/private state.
func (*Client) Unblock ¶
Unblock unblocks a user.
Endpoint: POST /api/v1/friendships/unblock/<user_id>/
func (*Client) Unfollow ¶
Unfollow unfollows a user.
Endpoint: POST /api/v1/friendships/destroy/<user_id>/
func (*Client) UnfollowHashtag ¶
UnfollowHashtag stops following a hashtag.
Endpoint: POST /api/v1/web/tags/unfollow/<name>/
func (*Client) UnlikeComment ¶
UnlikeComment removes a like from a comment.
Endpoint: POST /api/v1/media/<comment_id>/comment_unlike/
func (*Client) UnlikePost ¶
UnlikePost removes a like from a post.
Endpoint: POST /api/v1/media/<media_pk>/unlike/
func (*Client) UnmutePosts ¶
UnmutePosts undoes a previous MutePosts.
Endpoint: POST /api/v1/friendships/unmute_posts_or_story_from_follow/
func (*Client) UnsavePost ¶
UnsavePost removes a post from the user's saved collection.
Endpoint: POST /api/v1/media/<media_pk>/unsave/
func (*Client) UpdateProfessionalSettings ¶ added in v1.4.0
func (c *Client) UpdateProfessionalSettings(ctx context.Context, p UpdateProfessionalSettingsParams) (*AccountMutationResult[ProfessionalSettings], error)
UpdateProfessionalSettings changes only category ID and category visibility on an existing professional account. It cannot convert account type.
func (*Client) UpdateProfileFields ¶ added in v1.4.0
func (c *Client) UpdateProfileFields(ctx context.Context, p UpdateProfileFieldsParams) (*AccountMutationResult[ProfileFields], error)
UpdateProfileFields changes only full name, biography, and external URL.
type ClipsMetadata ¶
type ClipsMetadata struct {
OriginalSoundInfo *AudioInfo `json:"original_sound_info,omitempty"`
MusicInfo *AudioInfo `json:"music_info,omitempty"`
AudioRankingInfo *AudioInfo `json:"audio_ranking_info,omitempty"`
OriginalAudioTitle string `json:"original_audio_title,omitempty"`
}
ClipsMetadata is the reels-specific metadata attached to a Post when product_type == "clips".
type Comment ¶
type Comment struct {
ID string `json:"pk,omitempty"`
UserID string `json:"user_id,omitempty"`
User *User `json:"user,omitempty"`
Text string `json:"text,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
LikeCount int `json:"comment_like_count"`
HasLikedComment bool `json:"has_liked_comment"`
ChildCommentCount int `json:"child_comment_count"`
ParentCommentID string `json:"parent_comment_id,omitempty"`
Replies []*Comment `json:"child_comments,omitempty"`
Raw json.RawMessage `json:"-"`
}
Comment is a top-level or threaded comment on a post.
type Cookies ¶
type Cookies struct {
SessionID string `json:"sessionid"`
CSRFToken string `json:"csrftoken"`
DSUserID string `json:"ds_user_id"`
Datr string `json:"datr"`
Mid string `json:"mid"`
IgDid string `json:"ig_did"`
Rur string `json:"rur"`
IgNrcb string `json:"ig_nrcb"`
PsL string `json:"ps_l"`
PsN string `json:"ps_n"`
Wd string `json:"wd"`
}
Cookies holds the Instagram session cookies obtained from a browser export. SessionID, CSRFToken, and DSUserID are required; the rest help mimic a real browser session and reduce the chance of the request being blocked.
type CurrentAccount ¶ added in v1.4.0
type CurrentAccount struct {
AccountID string `json:"account_id"`
Username string `json:"username"`
Profile ProfileFields `json:"profile"`
IsPrivate bool `json:"is_private"`
IsProfessional bool `json:"is_professional"`
AccountType int `json:"account_type"`
}
CurrentAccount is the safe identity/profile projection of the authenticated account response. Contact and security data are never retained.
type DirectItem ¶ added in v1.4.0
type DirectItem struct {
ID string `json:"item_id"`
ThreadID string `json:"thread_id,omitempty"`
UserID string `json:"user_id,omitempty"`
ItemType string `json:"item_type,omitempty"`
Text string `json:"text,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
ClientContext string `json:"client_context,omitempty"`
IsSentByViewer bool `json:"is_sent_by_viewer,omitempty"`
Raw json.RawMessage `json:"-"`
}
DirectItem is one item in an Instagram Direct thread. Text is populated only for captured text items; attachments, reactions, vanish mode, and administrative events are intentionally left unsupported.
type DirectSendError ¶ added in v1.4.0
DirectSendError preserves the idempotency context for a failed or uncertain send so callers can safely reconcile or retry the same logical broadcast.
func (*DirectSendError) Error ¶ added in v1.4.0
func (e *DirectSendError) Error() string
func (*DirectSendError) Unwrap ¶ added in v1.4.0
func (e *DirectSendError) Unwrap() error
type DirectSendResult ¶ added in v1.4.0
type DirectSendResult struct {
RecipientID string `json:"recipient_id"`
ThreadID string `json:"thread_id"`
ItemID string `json:"item_id,omitempty"`
ClientContext string `json:"client_context"`
Status string `json:"status,omitempty"`
}
DirectSendResult identifies the created/resolved thread and broadcast item.
type DirectTextRequest ¶ added in v1.4.0
type DirectTextRequest struct {
RecipientID string `json:"recipient_id"`
Text string `json:"text"`
ThreadID string `json:"thread_id,omitempty"`
ClientContext string `json:"client_context,omitempty"`
RetryToken string `json:"retry_token,omitempty"`
}
DirectTextRequest identifies the sole recipient and text for a Direct message. ThreadID, ClientContext, and the authenticated RetryToken may be supplied together to safely retry an uncertain broadcast without repeating thread creation. For a new send, leave all three empty and the SDK generates a cryptographically random context.
type DirectThread ¶ added in v1.4.0
type DirectThread struct {
ID string `json:"thread_id"`
Title string `json:"thread_title,omitempty"`
Users []*User `json:"users,omitempty"`
Items []*DirectItem `json:"items,omitempty"`
LastActivityAt int64 `json:"last_activity_at,omitempty"`
IsGroup bool `json:"is_group,omitempty"`
IsPending bool `json:"is_pending,omitempty"`
Muted bool `json:"muted,omitempty"`
ReadState int `json:"read_state,omitempty"`
Raw json.RawMessage `json:"-"`
}
DirectThread is a conversation returned by the authenticated viewer's Instagram Direct inbox. Direct payloads are private; Raw must never be logged or persisted without explicit redaction.
type FriendshipStatus ¶
type FriendshipStatus struct {
Following bool `json:"following"`
FollowedBy bool `json:"followed_by"`
Blocking bool `json:"blocking"`
Muting bool `json:"muting"`
IsPrivate bool `json:"is_private"`
IncomingRequest bool `json:"incoming_request"`
OutgoingRequest bool `json:"outgoing_request"`
IsBestie bool `json:"is_bestie"`
IsRestricted bool `json:"is_restricted"`
IsFeedFavorite bool `json:"is_feed_favorite"`
}
FriendshipStatus describes the relationship between the viewer and a user.
type Hashtag ¶
type Hashtag struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
MediaCount int `json:"media_count"`
ProfilePicURL string `json:"profile_pic_url,omitempty"`
Following bool `json:"following"`
FollowingCount int `json:"following_count,omitempty"`
Raw json.RawMessage `json:"-"`
}
Hashtag describes a hashtag with profile metadata.
type ImageVersion ¶
type ImageVersion struct {
URL string `json:"url"`
Width int `json:"width"`
Height int `json:"height"`
}
ImageVersion describes one resolution of a post's image.
type Iterator ¶
type Iterator[T any] struct { // contains filtered or unexported fields }
Iterator is the generic paginating iterator returned by all list endpoints.
Usage:
it := client.GetPosts(username)
for it.Next(ctx) {
post := it.Item()
fmt.Println(post.Code, post.LikeCount)
}
if err := it.Err(); err != nil {
log.Fatal(err)
}
func (*Iterator[T]) Cursor ¶
Cursor returns the endpoint-specific next-page cursor. It is opaque and can be passed to WithCursor on a fresh iterator to resume in a later process.
func (*Iterator[T]) Item ¶
func (it *Iterator[T]) Item() T
Item returns the current item. Only valid after Next returns true.
func (*Iterator[T]) Next ¶
Next advances to the next item, fetching a new page if necessary. Returns false when there are no more items or an error occurred. Inspect Err.
func (*Iterator[T]) WithCursor ¶ added in v1.4.0
WithCursor starts the iterator from a cursor returned by Cursor. It must be called before Next or Collect. Cursor values are endpoint-specific and should be treated as opaque.
func (*Iterator[T]) WithMaxPages ¶
WithMaxPages caps the number of upstream requests the iterator will make. Returns the iterator for chaining. 0 means unlimited.
type Location ¶
type Location struct {
ID string `json:"pk,omitempty"`
ShortName string `json:"short_name,omitempty"`
Name string `json:"name,omitempty"`
Address string `json:"address,omitempty"`
City string `json:"city,omitempty"`
Lng float64 `json:"lng,omitempty"`
Lat float64 `json:"lat,omitempty"`
ExternalSource string `json:"external_source,omitempty"`
FacebookPlacesID string `json:"facebook_places_id,omitempty"`
MediaCount int `json:"media_count,omitempty"`
Raw json.RawMessage `json:"-"`
}
Location is a geo-tag attached to a post.
type LoginParams ¶ added in v1.3.0
type LoginParams struct {
Username string
Password string
// SidecarURL is the base URL of the social-login sidecar (e.g.
// "http://social-login:8090"). Required.
SidecarURL string
// ProxyURL, when set, is forwarded to the sidecar so the browser logs in
// from a residential egress (Instagram challenges datacenter IPs).
ProxyURL string
// VerificationCode is the email/SMS code for Instagram's login challenge
// (interposed from unfamiliar IPs). When empty, VerificationProvider is
// consulted after the challenge is detected.
VerificationCode string
// VerificationProvider, when set, is called to fetch the login challenge
// code on demand (e.g. read from the user's connected Gmail). It is only
// invoked if the sidecar reports a verification challenge and no
// VerificationCode was pre-supplied.
VerificationProvider func(ctx context.Context) (string, error)
// HTTPClient overrides the client used to talk to the sidecar. Optional.
HTTPClient *http.Client
}
LoginParams configures a credential login via the social-login sidecar.
Instagram gates login behind Bloks-encrypted, browser-only JavaScript that is impractical to reproduce in a pure-Go client. Rather than reimplement it, we delegate the interactive login to the headless-browser social-login sidecar (see sidecars/social-login), which drives the real web login and returns the session cookies. Those cookies are then used by the normal Client for all API calls.
type LoginResult ¶ added in v1.3.0
LoginResult holds the session minted by a credential login.
func Login ¶ added in v1.3.0
func Login(ctx context.Context, p LoginParams) (LoginResult, error)
Login performs a credential login through the social-login sidecar and returns the resulting session cookies. The caller passes the cookies to New to build an authenticated Client.
type MutationPreconditionError ¶ added in v1.4.0
MutationPreconditionError describes a locally rejected administration mutation. Field is an allowlisted field name and never contains a secret.
func (*MutationPreconditionError) Error ¶ added in v1.4.0
func (e *MutationPreconditionError) Error() string
func (*MutationPreconditionError) Unwrap ¶ added in v1.4.0
func (e *MutationPreconditionError) Unwrap() error
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithAPIAppID ¶ added in v1.4.0
WithAPIAppID overrides X-IG-App-ID on mobile API requests. It does not change the web app ID configured by WithAppID.
func WithAPIHost ¶ added in v1.4.0
WithAPIHost overrides the origin used by explicitly mobile API requests, including the fbsearch SERP endpoints. The default is https://i.instagram.com. Existing web endpoints continue to use the WWW host and the same Client, HTTP transport, and cookie header.
func WithAPIUserAgent ¶ added in v1.4.0
WithAPIUserAgent overrides the Instagram Android User-Agent used on mobile API requests. It does not change the web request profile configured by WithUserAgent.
func WithAppID ¶
WithAppID overrides X-IG-App-ID for existing web requests. The default (936619743392459) is Instagram Web's registered app ID. Use WithAPIAppID to override the separate mobile API request profile.
func WithHTTPClient ¶
WithHTTPClient replaces the default http.Client. Nil is ignored.
IMPORTANT: When supplying a custom client, leave the cookie jar nil. Instagram's 302-to-login responses include Set-Cookie: sessionid="" directives that will wipe the session if you use a CookieJar. All cookies are sent via the explicit Cookie header instead.
func WithMinRequestGap ¶
WithMinRequestGap sets the minimum time between consecutive read requests. Default: 4s. Lower values risk triggering Instagram's behavioural limiter.
func WithMinWriteGap ¶
WithMinWriteGap sets the minimum time between consecutive write requests (Follow, Like, Comment, Save, etc.). Default: 12s. Writes share a separate rate-limit budget from reads on Instagram's backend.
func WithPublishingLimits ¶ added in v1.4.0
WithPublishingLimits configures maximum decoded upload sizes. Values must be positive to replace the conservative defaults (25 MiB photos, 100 MiB video). Limits are enforced while reading and before any Instagram request is made.
func WithPublishingTimeouts ¶ added in v1.4.0
WithPublishingTimeouts configures the deadline for each upload request and for the complete processing/status wait. Positive values replace defaults.
func WithRateLimitCooldown ¶
WithRateLimitCooldown sets how long the client refuses requests after observing a rate-limit signal from Instagram (a "wait a few minutes" body or a 302-to-login redirect). Reads and writes have independent cooldown budgets.
Pass 0 to use the defaults (5m read, 15m write). Pass any positive value to override; pass a tiny value (e.g. 1ms) to effectively disable the circuit-breaker (not recommended). Write cooldowns are capped at 30 minutes so callers always retain a bounded recovery window.
func WithRetry ¶
WithRetry configures retry behaviour. Set maxAttempts to 0 to disable retries. Default: 3 attempts, 750ms exponential base.
func WithSkipSessionValidation ¶
func WithSkipSessionValidation() Option
WithSkipSessionValidation disables the initial session check inside New. Useful for offline tests or when the caller wants to defer validation.
func WithUserAgent ¶
WithUserAgent overrides the User-Agent string for existing web requests. Most desktop browser UAs are rejected with "useragent mismatch". Use WithAPIUserAgent to override the separate mobile API request profile.
func WithWWWHost ¶ added in v1.4.0
WithWWWHost overrides the origin used by existing web endpoints and web GraphQL requests. The default is https://www.instagram.com.
This option is primarily useful for private proxies and tests. The value must be an absolute HTTP(S) origin; a trailing slash is ignored.
type Page ¶
Page is one page of a paginated response. NextCursor is empty when there are no more results. Iterator-backed methods expose it through Cursor; pass it to WithCursor on a fresh iterator to fetch the following page.
type PageOptions ¶
type PageOptions struct {
// Cursor is the next_max_id (or equivalent) returned from a previous page.
// Leave empty to fetch the first page.
Cursor string
// Limit caps the number of items per request. Instagram clamps this server-side
// (typically 12-50 depending on the endpoint); 0 uses the endpoint default.
Limit int
}
PageOptions configures a paginated request.
type Place ¶
type Place struct {
Title string `json:"title,omitempty"`
Subtitle string `json:"subtitle,omitempty"`
Location *Location `json:"location,omitempty"`
}
Place is a search result wrapping a Location with extra subtitle text.
type Post ¶
type Post struct {
ID string `json:"id,omitempty"`
PK string `json:"pk,omitempty"`
Code string `json:"code,omitempty"`
MediaType MediaType `json:"media_type"`
ProductType string `json:"product_type,omitempty"`
TakenAt int64 `json:"taken_at,omitempty"`
Caption string `json:"caption_text,omitempty"`
CaptionUserID string `json:"caption_user_id,omitempty"`
Owner *User `json:"user,omitempty"`
LikeCount int `json:"like_count"`
CommentCount int `json:"comment_count"`
ViewCount int `json:"view_count,omitempty"`
PlayCount int `json:"play_count,omitempty"`
IGTVViewCount int `json:"igtv_view_count,omitempty"`
SaveCount int `json:"save_count,omitempty"`
OriginalWidth int `json:"original_width,omitempty"`
OriginalHeight int `json:"original_height,omitempty"`
VideoDurationS float64 `json:"video_duration,omitempty"`
HasLiked bool `json:"has_liked,omitempty"`
IsPinned bool `json:"is_pinned,omitempty"`
IsPaidPartner bool `json:"is_paid_partnership,omitempty"`
ImageVersions []ImageVersion `json:"image_versions,omitempty"`
VideoVersions []VideoVersion `json:"video_versions,omitempty"`
CarouselMedia []*Post `json:"carousel_media,omitempty"`
Mentions []string `json:"mentions,omitempty"`
Location *Location `json:"location,omitempty"`
ClipsMetadata *ClipsMetadata `json:"clips_metadata,omitempty"`
// PermalinkURL is constructed from the shortcode as
// https://www.instagram.com/p/<code>/ for posts and /reel/<code>/ for
// product_type==clips.
PermalinkURL string `json:"-"`
// Raw is the complete media payload from the source endpoint.
Raw json.RawMessage `json:"-"`
}
Post is a media item — photo, video, reel, carousel, or IGTV.
type ProfessionalAccountState ¶ added in v1.4.0
type ProfessionalAccountState struct {
AccountID string `json:"account_id"`
IsProfessional bool `json:"is_professional"`
IsBusiness bool `json:"is_business"`
AccountType int `json:"account_type"`
CategoryName string `json:"category_name,omitempty"`
Settings ProfessionalSettings `json:"settings"`
}
ProfessionalAccountState describes professional status and its reversible display settings. IsProfessional and AccountType are read-only.
type ProfessionalSettings ¶ added in v1.4.0
type ProfessionalSettings struct {
CategoryID string `json:"category_id" jsonschema:"required"`
DisplayCategory bool `json:"display_category" jsonschema:"required"`
}
ProfessionalSettings is the narrow professional-display allowlist. It does not permit account conversion, contact changes, ownership, or security work.
type ProfileFields ¶ added in v1.4.0
type ProfileFields struct {
FullName string `json:"full_name" jsonschema:"required"`
Biography string `json:"biography" jsonschema:"required"`
ExternalURL string `json:"external_url" jsonschema:"required"`
}
ProfileFields is the complete allowlist for profile administration. It intentionally excludes username, email, phone, and every security field.
type PublishError ¶ added in v1.4.0
type PublishError struct {
Stage string
UploadID string
ClientID string
Partial bool
Underlying error
}
PublishError reports the safe protocol stage and deterministic identifiers involved in a failure. It never retains media bytes, captions, or credentials.
func (*PublishError) Error ¶ added in v1.4.0
func (e *PublishError) Error() string
func (*PublishError) Unwrap ¶ added in v1.4.0
func (e *PublishError) Unwrap() []error
type PublishPhotoInput ¶ added in v1.4.0
type PublishPhotoInput struct {
Media UploadSource
Caption string
IdempotencyKey string
}
PublishPhotoInput is the typed input for a single-image feed publication.
type PublishReelInput ¶ added in v1.4.0
type PublishReelInput struct {
Media UploadSource
Thumbnail UploadSource
Caption string
IdempotencyKey string
}
PublishReelInput is the typed input for a Reel. Thumbnail is required because the captured Reel contract contains a separate thumbnail upload.
type PublishResult ¶ added in v1.4.0
type PublishResult struct {
MediaID string `json:"media_id"`
Code string `json:"code,omitempty"`
UploadID string `json:"upload_id"`
ClientID string `json:"client_id"`
Kind PublishedMediaKind `json:"kind"`
}
PublishResult identifies exactly one created media item and the deterministic identifiers used across upload, processing, and configure stages.
type PublishStoryInput ¶ added in v1.4.0
type PublishStoryInput struct {
Media UploadSource
Thumbnail *UploadSource
Caption string
IdempotencyKey string
}
PublishStoryInput is the typed input for a video Story. Thumbnail is required. Photo Story publishing is deliberately absent until separately captured.
type PublishedMediaKind ¶ added in v1.4.0
type PublishedMediaKind string
PublishedMediaKind identifies the captured configure/delete contract for a created media item.
const ( PublishedMediaPhoto PublishedMediaKind = "photo" PublishedMediaReel PublishedMediaKind = "reel" PublishedMediaStory PublishedMediaKind = "story" )
type RateLimitState ¶
type RateLimitState struct {
LastBlockedAt time.Time
LastReadAt time.Time
LastWriteAt time.Time
CooldownReadUntil time.Time
CooldownWriteUntil time.Time
WriteBlocked bool
BlockedReason string
CapacityLevel int // 0 = degraded, 3 = healthy (-1 = unknown)
PeakTime bool // x-ig-peak-time
PeakV2 bool // x-ig-peak-v2
ConnectionQuality string // x-fb-connection-quality verbatim
OriginRegion string // x-ig-origin-region
ServerRegion string // x-ig-server-region
LastServerElapsedMs int // x-ig-request-elapsed-time-ms
}
RateLimitState is the most recent rate-limit observation, parsed from both Instagram's response body cues ("wait a few minutes") and the soft signals Instagram exposes via response headers (x-ig-*, x-fb-connection-quality).
Instagram does NOT publish standard rate-limit headers. The following are the closest server-side hints we can act on:
- x-ig-capacity-level: 0–3, where 3 = healthy, 0 = degraded
- x-ig-peak-time: "1" if Instagram considers traffic at peak
- x-ig-peak-v2: secondary peak hint
- x-fb-connection-quality: e.g. "EXCELLENT; q=0.9, rtt=18, ..."
CooldownReadUntil / CooldownWriteUntil are set when Instagram returns the "Please wait a few minutes" body or a 302-to-login (the soft-block pattern). All subsequent requests of the same kind block until the cooldown elapses.
Use Client.RateLimit() to read, Client.WaitForCooldown() to block until clear.
type SearchResult ¶
type SearchResult struct {
Users []*User `json:"users,omitempty"`
Places []*Place `json:"places,omitempty"`
}
SearchResult bundles users, hashtags, and places returned by /web/search/topsearch/.
type SetPrivacyParams ¶ added in v1.4.0
type SetPrivacyParams struct {
ExpectedAccountID string `json:"expected_account_id" jsonschema:"required"`
Before *bool `json:"before" jsonschema:"required"`
After *bool `json:"after" jsonschema:"required"`
Confirm bool `json:"confirm" jsonschema:"required"`
}
SetPrivacyParams guards one public/private transition.
type Story ¶
type Story struct {
ID string `json:"pk,omitempty"`
MediaType MediaType `json:"media_type"`
TakenAt int64 `json:"taken_at,omitempty"`
ExpiringAt int64 `json:"expiring_at,omitempty"`
User *User `json:"user,omitempty"`
ImageVersions []ImageVersion `json:"image_versions,omitempty"`
VideoVersions []VideoVersion `json:"video_versions,omitempty"`
Audience string `json:"audience,omitempty"`
Raw json.RawMessage `json:"-"`
}
Story is one item from a user's story tray.
type StoryReel ¶
type StoryReel struct {
ID string `json:"id,omitempty"`
User *User `json:"user,omitempty"`
Title string `json:"title,omitempty"`
Items []*Story `json:"items,omitempty"`
HasMore bool `json:"-"`
LatestReelMedia int64 `json:"-"`
Raw json.RawMessage `json:"-"`
}
StoryReel is a story tray item — one user's set of stories or a highlight.
type TypeaheadSearchResult ¶ added in v1.4.0
type TypeaheadSearchResult struct {
Users []*User `json:"users"`
RankToken string `json:"rank_token,omitempty"`
}
TypeaheadSearchResult is the typed account context returned by the mobile keyword typeahead stream.
type UpdateProfessionalSettingsParams ¶ added in v1.4.0
type UpdateProfessionalSettingsParams struct {
ExpectedAccountID string `json:"expected_account_id" jsonschema:"required"`
Before *ProfessionalSettings `json:"before" jsonschema:"required"`
After *ProfessionalSettings `json:"after" jsonschema:"required"`
Confirm bool `json:"confirm" jsonschema:"required"`
}
UpdateProfessionalSettingsParams guards reversible display-only settings.
type UpdateProfileFieldsParams ¶ added in v1.4.0
type UpdateProfileFieldsParams struct {
ExpectedAccountID string `json:"expected_account_id" jsonschema:"required"`
Before *ProfileFields `json:"before" jsonschema:"required"`
After *ProfileFields `json:"after" jsonschema:"required"`
Confirm bool `json:"confirm" jsonschema:"required"`
}
UpdateProfileFieldsParams requires a complete before/after pair and an explicit confirmation. ExpectedAccountID binds the operation to one account.
type UploadSource ¶ added in v1.4.0
type UploadSource struct {
Reader io.Reader
Filename string
MIMEType string
Size int64
Width int
Height int
Duration time.Duration
}
UploadSource describes a bounded media stream. Size is the exact decoded byte length, not a base64 length. Reader is consumed once by a publish call.
type User ¶
type User struct {
ID string `json:"pk_id,omitempty"`
Username string `json:"username,omitempty"`
FullName string `json:"full_name,omitempty"`
Biography string `json:"biography,omitempty"`
ExternalURL string `json:"external_url,omitempty"`
ProfilePicURL string `json:"profile_pic_url,omitempty"`
ProfilePicURLHD string `json:"profile_pic_url_hd,omitempty"`
IsPrivate bool `json:"is_private,omitempty"`
IsVerified bool `json:"is_verified,omitempty"`
IsBusiness bool `json:"is_business,omitempty"`
IsProfessional bool `json:"is_professional_account,omitempty"`
BusinessCategory string `json:"business_category_name,omitempty"`
Category string `json:"category_name,omitempty"`
FollowerCount int `json:"follower_count,omitempty"`
FollowingCount int `json:"following_count,omitempty"`
MediaCount int `json:"media_count,omitempty"`
TotalIGTVCount int `json:"total_igtv_videos,omitempty"`
HasReels bool `json:"has_clips,omitempty"`
HasGuides bool `json:"has_guides,omitempty"`
HasChaining bool `json:"has_chaining,omitempty"`
HasHighlightReels bool `json:"has_highlight_reels,omitempty"`
HideLikeAndViewCnts bool `json:"hide_like_and_view_counts,omitempty"`
IsBusinessOwned bool `json:"is_business_owned_by_viewer,omitempty"`
PublicEmail string `json:"public_email,omitempty"`
PublicPhone string `json:"public_phone_number,omitempty"`
ContactPhone string `json:"contact_phone_number,omitempty"`
AddressStreet string `json:"address_street,omitempty"`
City string `json:"city_name,omitempty"`
Zip string `json:"zip,omitempty"`
AccountType int `json:"account_type,omitempty"`
Pronouns []string `json:"pronouns,omitempty"`
SearchSERPType string `json:"search_serp_type,omitempty"`
SearchSocialContext string `json:"search_social_context,omitempty"`
SocialContext string `json:"social_context,omitempty"`
IsSearchBoosted bool `json:"is_verified_search_boosted,omitempty"`
FriendshipStatus *FriendshipStatus `json:"friendship_status,omitempty"`
// Raw is the complete user payload from the source endpoint.
// It lets callers access fields that aren't yet typed.
Raw json.RawMessage `json:"-"`
}
User represents an Instagram user/profile. Fields are populated based on which endpoint returned the data; not all fields are present everywhere.
IDs are strings because Instagram returns 64-bit numeric IDs that exceed JS Number safe range and are sometimes serialised as strings, sometimes as numbers. The client normalises to strings.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
instagram-account-inventory
command
Command instagram-account-inventory captures a secret-scrubbed, read-only contract for the authenticated account administration surface.
|
Command instagram-account-inventory captures a secret-scrubbed, read-only contract for the authenticated account administration surface. |
|
instagram-direct-inventory
command
Command instagram-direct-inventory validates and redacts a burner-account HAR containing the four Instagram Direct contracts used by the SDK.
|
Command instagram-direct-inventory validates and redacts a burner-account HAR containing the four Instagram Direct contracts used by the SDK. |
|
instagram-login-probe
command
Command instagram-login-probe is an end-to-end inventory smoke test.
|
Command instagram-login-probe is an end-to-end inventory smoke test. |
|
instagram-publish-inventory
command
Command instagram-publish-inventory validates and redacts burner-only HAR captures for Instagram photo, Reel, and video Story publishing.
|
Command instagram-publish-inventory validates and redacts burner-only HAR captures for Instagram photo, Reel, and video Story publishing. |
|
instagram-search-inventory
command
Command instagram-search-inventory captures a secret-scrubbed inventory of Instagram's private keyword-search surfaces.
|
Command instagram-search-inventory captures a secret-scrubbed inventory of Instagram's private keyword-search surfaces. |
|
Package mcp exposes the instagram-go instagram.Client surface as a set of MCP (Model Context Protocol) tools that any host application can mount on its own MCP server.
|
Package mcp exposes the instagram-go instagram.Client surface as a set of MCP (Model Context Protocol) tools that any host application can mount on its own MCP server. |
|
Package meta implements the official Meta Graph and Marketing APIs for Instagram professional accounts.
|
Package meta implements the official Meta Graph and Marketing APIs for Instagram professional accounts. |
|
mcp
Package mcp exposes the official Meta Graph client through an independent MCP provider.
|
Package mcp exposes the official Meta Graph client through an independent MCP provider. |