This is sample code that uses the media/upload package to upload media files to Twitter.
First, initialize the media upload with the following code.
res, err := Initialize(client, &types.InitializeInput{
MediaType: types.MediaTypePNG,
TotalBytes: len(fileBytes),
Shared: false,
MediaCategory: types.MediaCategoryTweetImage,
})You can append media data in two ways:
appendRes, err := Append(client, &types.AppendInput{
MediaID: mediaID,
Media: bytes.NewReader(fileBytes),
SegmentIndex: 0,
})In this example, the file is divided into 10 chunks for multi-segment upload.
chunkSize := len(fileBytes) / 10
segmentIndex := 0
for i := 0; i < len(fileBytes); i += chunkSize {
end := min(i+chunkSize, len(fileBytes))
chunk := fileBytes[i:end]
appendRes, err := Append(client, &types.AppendInput{
MediaID: mediaID,
Media: bytes.NewReader(chunk),
SegmentIndex: segmentIndex,
})
segmentIndex++
}After appending all media data, finalize the upload.
finalizeRes, err := Finalize(client, &types.FinalizeInput{
MediaID: mediaID,
})You can post a tweet with the uploaded media.
postedID, err := PostWithMedia(client, "post with a media by using gotwi", mediaID)-
Set environment variables.
export GOTWI_API_KEY=your-api-key export GOTWI_API_KEY_SECRET=your-api-key-secret export GOTWI_ACCESS_TOKEN=your-access-token export GOTWI_ACCESS_TOKEN_SECRET=your-access-token-secret
-
Run the example with default settings (single segment upload).
go run . -
Run with multi-segment upload.
go run . multi -
Run with multi-segment upload and post a tweet.
go run . multi post
- The example uses a sample PNG file (
sample.png) for demonstration. - Make sure you have the correct file permissions and the file exists in the same directory.
- The media upload process consists of three steps: Initialize, Append, and Finalize.
- You can choose between single-segment and multi-segment upload based on your needs.