Skip to content

Instantly share code, notes, and snippets.

@Nick-smallworld
Created February 28, 2022 10:06
Show Gist options
  • Select an option

  • Save Nick-smallworld/84bd44e11ccb752feebde41d2266a8b1 to your computer and use it in GitHub Desktop.

Select an option

Save Nick-smallworld/84bd44e11ccb752feebde41d2266a8b1 to your computer and use it in GitHub Desktop.

Revisions

  1. Nick-smallworld created this gist Feb 28, 2022.
    158 changes: 158 additions & 0 deletions create_tweet.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,158 @@
    // Rewrote "create_tweet.js" using axios, instead of got.
    // https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/Manage-Tweets/create_tweet.js
    // License: Apache 2.0
    // Worked under the below environment
    // node v16.4.0
    // "axios": "^0.26.0",
    // "crypto": "^1.0.1",
    // "oauth-1.0a": "^2.2.6",
    // "querystring": "^0.2.1",
    // "readline": "^1.3.0"


    const axios = require('axios');
    const crypto = require('crypto');
    const OAuth = require('oauth-1.0a');
    const qs = require('querystring');

    const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
    });


    // The code below sets the consumer key and consumer secret from your environment variables
    // To set environment variables on macOS or Linux, run the export commands below from the terminal:
    // export CONSUMER_KEY='YOUR-KEY'
    // export CONSUMER_SECRET='YOUR-SECRET'
    const consumer_key = process.env.CONSUMER_KEY;
    const consumer_secret = process.env.CONSUMER_SECRET;


    // Be sure to add replace the text of the with the text you wish to Tweet.
    // You can also add parameters to post polls, quote Tweets, Tweet with reply settings, and Tweet to Super Followers in addition to other features.
    const data = {
    "text": "Hello world!"
    };

    const endpointURL = `https://api.twitter.com/2/tweets`;

    // this example uses PIN-based OAuth to authorize the user
    const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write';
    const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
    const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
    const oauth = OAuth({
    consumer: {
    key: consumer_key,
    secret: consumer_secret
    },
    signature_method: 'HMAC-SHA1',
    hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
    });

    async function input(prompt) {
    return new Promise(async (resolve, reject) => {
    readline.question(prompt, (out) => {
    readline.close();
    resolve(out);
    });
    });
    }

    async function requestToken() {
    const authHeader = oauth.toHeader(oauth.authorize({
    url: requestTokenURL,
    method: 'POST'
    }));

    const req = await axios.post(requestTokenURL, {}, {
    headers: {
    Authorization : authHeader["Authorization"]
    },
    });
    if (req) {

    return qs.parse(req.data);

    } else {
    throw new Error('Cannot get an OAuth request token');
    }
    }


    async function accessToken({
    oauth_token,
    oauth_token_secret
    }, verifier) {
    const authHeader = oauth.toHeader(oauth.authorize({
    url: accessTokenURL,
    method: 'POST'
    }));
    const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
    const req = await axios.post(path, {},{
    headers: {
    Authorization : authHeader["Authorization"]
    }
    });
    if (req.data) {
    return qs.parse(req.data);
    } else {
    throw new Error('Cannot get an OAuth request token');
    }
    }


    async function getRequest({
    oauth_token,
    oauth_token_secret
    }) {

    const token = {
    key: oauth_token,
    secret: oauth_token_secret
    };

    const authHeader = oauth.toHeader(oauth.authorize({
    url: endpointURL,
    method: 'POST'
    }, token));

    const req = await axios.post(endpointURL, data, {

    responseType: 'json',
    headers: {
    Authorization: authHeader["Authorization"],
    'user-agent': "v2CreateTweetJS",
    'content-type': "application/json",
    'accept': "application/json"
    }
    });
    if (req.data) {
    return req.data;
    } else {
    throw new Error('Unsuccessful request');
    }
    }


    (async () => {
    try {
    // Get request token
    const oAuthRequestToken = await requestToken();
    // Get authorization
    authorizeURL.searchParams.append('oauth_token', oAuthRequestToken.oauth_token);
    console.log('Please go here and authorize:', authorizeURL.href);
    const pin = await input('Paste the PIN here: ');
    // Get the access token
    const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim());
    // Make the request
    const response = await getRequest(oAuthAccessToken);
    console.dir(response, {
    depth: null
    });
    } catch (e) {
    console.log(e);
    process.exit(-1);
    }
    process.exit();
    })();