post a tweet in javascript

To post a tweet using JavaScript, follow these steps:

  1. Create a Twitter developer account and create a new Twitter app to generate your API keys and access tokens.

  2. Install the oauth-1.0a package to handle the OAuth authentication for making requests to the Twitter API.

index.tsx
npm install oauth-1.0a --save
30 chars
2 lines
  1. Generate the OAuth header with your keys and access tokens.
index.tsx
const oauth = require('oauth-1.0a');
const crypto = require('crypto');

const oauthSignature = oauth({
  consumer: {
    key: 'YOUR_CONSUMER_KEY',
    secret: 'YOUR_CONSUMER_SECRET'
  },
  signature_method: 'HMAC-SHA1',
  hash_function(baseString, key) {
    return crypto.createHmac('sha1', key).update(baseString).digest('base64');
  }
});

const oauthToken = {
  key: 'YOUR_ACCESS_TOKEN',
  secret: 'YOUR_ACCESS_TOKEN_SECRET'
};

const requestData = {
  url: 'https://api.twitter.com/1.1/statuses/update.json',
  method: 'POST',
  data: {
    status: 'Hello, World!'
  }
};

const headers = oauthSignature.toHeader(oauthSignature.authorize(requestData, oauthToken));
670 chars
29 lines
  1. Use the fetch() function to make a POST request to the Twitter API using the OAuth header and tweet text.
index.tsx
fetch('https://api.twitter.com/1.1/statuses/update.json', {
  method: 'POST',
  headers: {
    Authorization: headers.Authorization,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: 'status=Hello%20World!'
})
  .then(response => response.json())
  .then(tweet => console.log(tweet))
  .catch(error => console.error(error));
344 chars
12 lines

This will make a POST request to the Twitter API to post a new tweet with the text "Hello, World!" and return the tweet object in the console.

gistlibby LogSnag