Search code examples
node.jstwitteraws-lambdatwitter-oauth

Node AWS Lambda POST to Twitter with User context Auth


I am attempting to create a Node lambda on AWS which will authenticate with the Twitter API, via the twit npm module, in User Context. So that the lambda can then upload a GIF and then once uploaded, tweet on the user's timeline using the returned media_id.

I have created a twitter app etc. It works, however it is posting the tweet to the account associated with the app, instead of the user's timeline. Here is my entire lambda code:

const fs = require('fs');
const Twit = require('twit');

var T = new Twit({
    consumer_key:         '...',
    consumer_secret:      '...',
    access_token:         '...',
    access_token_secret:  '...'
});


module.exports.oauth = (event, context, callback) => {

        var b64content = fs.readFileSync('./testGIF.gif', { encoding: 'base64' })

        // POST the media to Twitter
        T.post('media/upload', { media_data: b64content }, function (err, data, response) {
          // assign alt text to the media, for use by screen readers etc
          var mediaIdStr = data.media_id_string
          var altText = "Alt text"
          var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }

          T.post('media/metadata/create', meta_params, function (err, data, response) {
            if (!err) {
              // reference the media and post a tweet (media will attach to the tweet)
              var params = { status: 'Testing, GIF Sharing', media_ids: [mediaIdStr] }

              T.post('statuses/update', params, function (err, data, response) {
                console.log(data)
              })
            }
          })
        })

  const response = {
    statusCode: 200,
  };

  callback(null, response);

};

Any help would be much appreciated!


Solution

  • You are currently using tokens for the user account associated with the app.

    You'll need to obtain an OAuth token on the user's behalf and use that to make authorized calls to Twitter's APIs.

    You need to first create a webpage for your twitter app, then do any of the following:

    • implement a twitter signin to directly capture an OAUTH token
    • implement a three legged authorization to directly capture an OAUTH token
    • use a PIN-based authorization

    Once you have captured OAUTH token for the user, you can passed it on to your lambda to be used to initialize the Twit client.

    https://dev.twitter.com/oauth/overview