kitaro-tn
12/28/2017 - 7:00 AM

twitter get retweet by lambda function

twitter get retweet by lambda function

'use strict';

const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
const querystring = require("querystring");
const http = require("https");
const TWITTER_API_URL = "https://api.twitter.com"
const TWITTER_HOSTNAME = "api.twitter.com"

/**
 * Get tweet id from DyanamoDB
 */
function getTeeetIds() {
  return [];
}

/**
 * API auth
 * @param {String} accessKey
 * @param {String} secretKey
 * @see https://developer.twitter.com/en/docs/basics/authentication/api-reference/token
 */
function auth(accessKey, secretKey) {
  return new Promise((resolve, reject) => {

    let encodedBearerToken = new Buffer(`${accessKey}:${secretKey}`).toString('base64');
    let postData = querystring.stringify({ "grant_type": "client_credentials" });
    let options = {
      hostname: TWITTER_HOSTNAME,
      port: '443',
      path: '/oauth2/token',
      method: 'POST',
      headers: {
        'Authorization': `Basic ${encodedBearerToken}`,
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    console.log('Start request');
    let req = http.request(options, (res) => {
      console.log(`STATUS: ${res.statusCode}`);
      // console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        console.log(chunk);
        console.log(`BODY: ${chunk}`);
        resolve(JSON.parse(chunk));
      });

      res.on('end', () => {
        console.log('No more data in response.');
      });

    }).on('error', (e) => {
      console.error(e);
      reject(e);
      // console.error(`problem with request: ${e.message}`);
    });

    console.log(postData);

    req.write(postData);
    req.end();
  });
}

/**
 * Call retweet API
 * @param {String} bearerToken
 * @param {String} tweetId
 * @return {Object} response
 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
 */
function getRetwet(bearerToken, tweetId) {
  return new Promise((resolve, reject) => {
    resolve(tweetId);
    // let encodedBearerToken = new Buffer(`${accessKey}:${secretKey}`).toString('base64');
    // let postData = querystring.stringify({ "grant_type": "client_credentials" });
    // let options = {
    //   hostname: TWITTER_HOSTNAME,
    //   port: '443',
    //   path: '/oauth2/token',
    //   method: 'POST',
    //   headers: {
    //     'Authorization': `Basic ${encodedBearerToken}`,
    //     'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    //     'Content-Length': Buffer.byteLength(postData)
    //   }
    // };
    //
    // console.log('Start request');
    // let req = http.request(options, (res) => {
    //   console.log(`STATUS: ${res.statusCode}`);
    //   // console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    //   res.setEncoding('utf8');
    //   res.on('data', (chunk) => {
    //     console.log(chunk);
    //     console.log(`BODY: ${chunk}`);
    //     resolve(JSON.parse(chunk));
    //   });
    //
    //   res.on('end', () => {
    //     console.log('No more data in response.');
    //   });
    //
    // }).on('error', (e) => {
    //   console.error(e);
    //   reject(e);
    //   // console.error(`problem with request: ${e.message}`);
    // });
    //
    // console.log(postData);
    //
    // req.write(postData);
    // req.end();
  });
}

/**
 * Save s3
 */

function main(event, context, callback) {
  console.log(new Buffer('hoge').toString('base64'));
  console.log(new Buffer('aG9nZQ==', 'base64').toString('ascii'));
  let tweetIds = getTeeetIds();
  if (typeof process.env.TWITTER_ACCESS_KEY == "undefined" || typeof process.env.TWITTER_SECRET_KEY == "undefined") {
    if (callback) {
      callback("API key not found.");
    } else {
      console.error("API key not found.");
      process.exit(1);
    }
  }

  console.log("Authorization");
  auth(process.env.TWITTER_ACCESS_KEY, process.env.TWITTER_SECRET_KEY).then((data) => {
    console.log(data.access_token);
    return data.access_token;
  }).then(getRetwet).catch((error) => {
    if (callback) {
      callback(error);
    } else {
      console.error(error);
      process.exit(1);
    }
  }).then((data) => {
    console.log(data);
    if (callback) {
      callback(null, "Success");
    } else {
      console.log("Success");
      process.exit();
    }
  });
}

exports.lambdaHandler = function(event, context, callback) {
  main(event, context, callback);
}

main();