Search code examples
node.jsimagetwittertwitter-oauth

Twitter api v1 problem with authorization of media_ids while sending a post


I am building a twitter bot that sends a twitter post with a media included in it. I am able send a post with only text in it with no problem. But the following error is thrown when I try to add media_ids to the post:

[ { code: 32, message: 'Could not authenticate you.' } ]

Here is my function to send a twitter post:

const axios = require('axios')
const fs = require('fs')
const Path = require('path')
const Twitter = require('twitter')
require('dotenv').config()

const client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
})




async function sendTwitterPost() {
  return new Promise(async (resolve, reject) => {
    try {
      const contents = await fs.promises.readFile('./temp/image.png', {encoding: 'base64'})
      console.log("Got the image, uploading image to twitter...")
      const res = await client.post('media/upload', {
        media_data: contents,
        media_category: 'tweet_image'
      })
      console.log(res.media_id + " Image uploaded, sending twitter post...")
      let mediaIds = []
      mediaIds.push(res.media_id)
      await client.post('statuses/update', { 
        status: 'New event occured!',
        media_ids: mediaIds
      })
      
      resolve("Twitter post successfully sent")
    }
    catch(err){
      console.log(err)
      reject("Error while sending twitter post")
    }
  })
}

My tokens have read-write permission, and as I said I am able to send a post with only text in it. Also I have elevated access.


Solution

  • I fixed it by changing

    let mediaIds = []
    mediaIds.push(res.media_id)
    await client.post('statuses/update', { 
      status: 'New event occured!',
      media_ids: mediaIds
    })
    

    to

    await client.post('statuses/update', { 
      status: 'New event occured!',
      media_ids: res.media_id_string
    })
    

    It seems that string is needed for the media_ids field for twitter api v1 with twitter package.