Open In App

Tweet using Node.js and Twitter API

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Twitter is a social media website, with 450 million monthly active users (as of 2022). These users interact with each other using tweets . A tweet can contain Text, Video, GIF, Image. User post this tweet and other user can Like, Reply, Retweet, Bookmark, Mention other user in reply etc. 

The Twitter API is a toolkit that lets developers work with Twitter’s data and features. It allows them to build programs that can read and write Twitter data, and perform other functions too. The API has lots of “endpoints” that developers can use to get different kinds of Twitter data. For example, they can get tweets, user information, trending topics, and more. These endpoints use the REST architecture, which makes it easy for developers to communicate with Twitter’s servers. Overall, the Twitter API is a powerful tool that gives developers access to a wide range of Twitter data and functionality.

Problem Statement: To create and tweet a post (without image/media and with image/media) using Node.js and twitter-api-v2 library.

 

Approach: To create and post a tweet you can follow the steps below:

  • Create a Twitter developer account & get API credentials  (Link to create your developer account – https://developer.twitter.com/en )
  • Create a new node project and initialize npm write the following commands in shell.
mkdir tweetPoster
cd tweetPoster
npm init
  • install twitter-api-v2 library using the following command in the shell.
npm install twitter-api-v2
  • Create an index.js file inside tweetPoster directory.
  •  import twitter-api-v2 library in index.js 
const { TwitterApi } = require("twitter-api-v2");
  • Create a Twitter client by filling in your API keys and secrets, this will authenticate your account and allow you to use Twitter API to create requests and get responses. 
const client = new TwitterApi({
      appKey: "**",
      appSecret: "**",
      accessToken: "**",
      accessSecret: "**",
      bearerToken:"**",
});
  • Provide read and write controls to your client so it can create new tweets 
const rwClient = client.readWrite;
  • ( For only text tweets) create a textTweet asynchronised function and then create a try-catch, inside the try block, create await tweet request using rwClient.v2, and inside .tweet() you can put any text in string format you want to tweet then put a console.log(“success”). So, in case of a tweet is posted successfully, success will get printed in the terminal. Now, add console.log(error) in the catch block. So, in case of any failure, error will get printed in the terminal.
const textTweet = async () => {
      try {
        await rwClient.v2.tweet(
            "This tweet has been created using nodejs");
        console.log("success");
      } catch (error) {
        console.error(error);
      }
};
  • (For text tweet with media) create a mediaTweet asynchronised function and then create a try-catch, inside the try block, create a mediaId const, and create await uploadMedia request (put the path of the image you want to post in place of “image_path”). The uploadMedia method is used to upload the media file, and the mediaId variable is assigned the unique identifier that Twitter assigns to the uploaded media. create await tweet request using rwClient.v2 and inside .tweet() you can put a JavaScript object.
{
      text: "any text you wish to post with image/media ",
      media: { media_ids: [mediaId] },
}
  •  Then put a console.log(“success”). So, in case of a tweet is posted successfully, success will get printed in the terminal. Now, add console.log(error) in the catch block. So, in case of any failure, error will get printed in the terminal.
const mediaTweet = async () => {
      try {
        const mediaId = await client.v1.uploadMedia("image_path");
        await rwClient.v2.tweet({
              text: "Twitter is a fantastic social network. Look at this:",
              media: { media_ids: [mediaId] },
        });
        console.log("success");
      } catch (e) {
        console.error(e);
      }
};
  • Call any or both textTweet() & mediaTweet() methods.
textTweet();
mediaTweet();
  • Run index.js in terminal.
node index.js

Javascript




// Import twitter-api-v2
const { TwitterApi } = require("twitter-api-v2");
  
// Fill your API credentials
const client = new TwitterApi({
    appKey: "**",
    appSecret: "**",
    accessToken: "**",
    accessSecret: "**",
    bearerToken: "**",
});
  
// Provide read write controls
const rwClient = client.readWrite;
  
// Create textTweet function which post
// a text only tweet
const tweetText = async () => {
    try {
  
        // Use .tweet() method and pass the
        // text you want to post
        await rwClient.v2.tweet(
            "This tweet has been created using nodejs");
  
        console.log("success");
    } catch (error) {
        console.log(error);
    }
};
  
// Create tweet function which post
// tweet with media and text
const mediaTweet = async () => {
    try {
  
        // Create mediaID 
        const mediaId = await client.v1.uploadMedia(
  
            // Put path of image you wish to post
            "./1605232393098780672example.png"
        );
  
        // Use tweet() method and pass object with text 
        // in text feild and media items in media feild
        await rwClient.v2.tweet({
            text: 
"Twitter is a fantastic social network. Look at this:",
            media: { media_ids: [mediaId] },
        });
        console.log("success");
    } catch (error) {
        console.log(error);
    }
};
  
// Call any of methods and you are done 
textTweet();
mediaTweet();


Output:

output of the above program

Tweet Samples:

sample of only text tweet



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads