attach image
This commit is contained in:
@@ -1,11 +1,14 @@
|
||||
package output
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/michimani/gotwi"
|
||||
"github.com/michimani/gotwi/media/upload"
|
||||
uploadtypes "github.com/michimani/gotwi/media/upload/types"
|
||||
"github.com/michimani/gotwi/tweet/managetweet"
|
||||
"github.com/michimani/gotwi/tweet/managetweet/types"
|
||||
)
|
||||
@@ -41,15 +44,61 @@ func (to *twitteroutput) newOAuth1Client(accessToken, accessSecret string) error
|
||||
return err
|
||||
}
|
||||
|
||||
func (to *twitteroutput) Write(str string) error {
|
||||
func (to *twitteroutput) Write(str string, images []Image) error {
|
||||
mediaIDs := make([]string, 0, len(images))
|
||||
for _, img := range images {
|
||||
mediaID, err := to.uploadImage(img)
|
||||
if err != nil {
|
||||
return fmt.Errorf("uploading %s: %w", img.Filename, err)
|
||||
}
|
||||
mediaIDs = append(mediaIDs, mediaID)
|
||||
}
|
||||
|
||||
p := &types.CreateInput{
|
||||
Text: gotwi.String(str),
|
||||
}
|
||||
if len(mediaIDs) > 0 {
|
||||
p.Media = &types.CreateInputMedia{
|
||||
MediaIDs: mediaIDs,
|
||||
}
|
||||
}
|
||||
|
||||
_, err := managetweet.Create(context.Background(), to.client, p)
|
||||
return err
|
||||
}
|
||||
|
||||
func (to *twitteroutput) uploadImage(img Image) (string, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
initialized, err := upload.Initialize(ctx, to.client, &uploadtypes.InitializeInput{
|
||||
MediaCategory: uploadtypes.MediaCategoryTweetImage,
|
||||
MediaType: uploadtypes.MediaType(img.ContentType),
|
||||
TotalBytes: len(img.Data),
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
mediaID := initialized.Data.MediaID
|
||||
|
||||
_, err = upload.Append(ctx, to.client, &uploadtypes.AppendInput{
|
||||
MediaID: mediaID,
|
||||
Media: bytes.NewReader(img.Data),
|
||||
SegmentIndex: 0,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
_, err = upload.Finalize(ctx, to.client, &uploadtypes.FinalizeInput{
|
||||
MediaID: mediaID,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return mediaID, nil
|
||||
}
|
||||
|
||||
func (to *twitteroutput) GetName() string {
|
||||
return "twitter"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user