Skip to content

Instantly share code, notes, and snippets.

@larrasket
Created October 9, 2022 09:18
Show Gist options
  • Save larrasket/eb8e6f483f9321a330e84ba3e9c4e93b to your computer and use it in GitHub Desktop.
Save larrasket/eb8e6f483f9321a330e84ba3e9c4e93b to your computer and use it in GitHub Desktop.
Post media to twitter using go-twitter
func PublishTW(file string) {
config := oauth1.NewConfig(token.TWcon, token.TWconSEC)
token := oauth1.NewToken(token.TW, token.TWsec)
httpClient := config.Client(oauth1.NoContext, token)
b := &bytes.Buffer{}
form := multipart.NewWriter(b)
fw, err := form.CreateFormFile("media", file)
if err != nil {
panic(err)
}
opened, err := os.Open(file)
if err != nil {
panic(err)
}
_, err = io.Copy(fw, opened)
if err != nil {
panic(err)
}
// post picture
form.Close()
resp, err :=
httpClient.Post("https://upload.twitter.com/1.1/media/upload.json?media_category=tweet_image",
form.FormDataContentType(), bytes.NewReader(b.Bytes()))
if err != nil {
fmt.Printf("Error: %s\n", err)
}
defer resp.Body.Close()
m := &MediaUpload{}
_ = json.NewDecoder(resp.Body).Decode(m)
mid := strconv.Itoa(m.MediaId)
resp, err = httpClient.PostForm("https://api.twitter.com/1.1/statuses/update.json",
url.Values{"status": {"Post the status!"}, "media_ids": {mid}})
if err != nil {
fmt.Printf("Error: %s\n", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment