36
Programmatically Tweeting with NodeJS

This post is for day 1 of my #100DaysOfCode. In this post I'll be discussing how to programmatically tweet to Twitter using NodeJS.
You'll eventually find yourself within the Twitter Developer Dashboard where you can generate authentication tokens that will be essential to making requests.

Make sure you have NodeJS installed
I prefer yarn, but you can use npm instead if you prefer
yarn init -y
yarn add twitter-lite
yarn add dotenv
Your
package.json
file should now look like this:{
"name": "programmatic-tweeting-with-nodejs",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"dot-env": "^0.0.1",
"twitter-lite": "^1.1.0"
}
}
The
.env
file should look like this:consumer_key = '<CONSUMER KEY>'
consumer_secret = '<CONSUMER SECRET>'
access_token_key = '<ACCESS TOKEN>'
access_token_secret = '<ACCESS TOKEN>'
Just make sure you replace the
<>
text with the tokens Twitter provided you.Make sure you do not commit your .env file to Github or any other version control systems. These tokens are very important, and should not be shared with anyone!
const twitter = require('twitter-lite')
require('dotenv').config()
const client = new twitter(config)
client
.post('statuses/update', { status: 'Hello World' })
.then(result => {
console.log('You successfully tweeted this : "' + result.text + '"')
})
.catch(console.error)
Step #4 is creating a POST request to Twitter's endpoint
statuses/update
with the parameter status = 'Hello World'
.Now type
node index.js
into your terminal and press enter. This will generate a Tweet with the text "Hello World".I hope this article was helpful, let me know if you have any questions, comments, or suggestions on Twitter @codybontecou