How to like and retweet using the Twitter v2 API

Elon musk thumbs up

In this final Twitter API tutorial, I will show you how to like and retweet using the Twitter API.

Table of contents

Further look at the documentation

After this final tutorial, you should be able to do everything you want using the API. Have a look at the documentation here and you can search for what you want to do.

For example, if we wanted to delete a tweet, we could go to this section of the docs and follow the instructions

Delete a tweet

Step 1: Search for tweets

Searching for tweets is easy. For this step, we will use the twitterBearer we created in the previous blog post.

We can then add the following to our index.js file.

index.js
const whereTakenTweets = await twitterBearer.v2.search('#WhereTaken There were');

for await (const tweet of whereTakenTweets) {
    console.log(tweet);
}

In my console, it has found the latest 10 tweets that match this criteria, and it has sent back the contents of the tweet under text and the id. Don't worry about the edit_history_tweet_ids, that is not needed.

Where taken tweet history

Now we have the tweets, we can start liking and retweeting them!

Step 2: Like tweets

To like a tweet, it is very simple, we need to call the following

await client.v2.like('<APP_ID>', '<TWEET_ID>');

The APP_ID should be an environment variable, as we created this in the previous tutorial. The TWEET_ID is the id that was sent back in step 1.

If we wanted to like all of the tweets we found we could do

index.js
const like = async () => {
    const whereTakenTweets = await twitterBearer.v2.search('#Worldle');

    for await (const tweet of whereTakenTweets) {
        await twitterClient.v2.like(process.env.APP_ID, tweet.id);
    }
}

Step 3: Retweet a tweet

Retweeting is very similar to liking. All we need to do is call the retweet method.

If we wanted to retweet the first tweet we found while searching, we could do this

index.js
const retweet = async () => {
    const whereTakenTweets = await twitterBearer.v2.search('#WhereTaken There were');

    const tweetID = whereTakenTweets.data.data[0].id;
    await twitterClient.v2.retweet(process.env.APP_ID, tweetID);
}

And there you have it. You should now be in a position where you can make whatever Twitter bot you like using these tutorials and the documentation.


Image of the Author, Ryan Carmody

About the Author

Open for work

Hi, I'm Ryan from Adelaide, South Australia.

I'm a web developer and computer science tutor. I also rock climb, play wheelchair basketball and brew beer.

Check out some of the games I made

Smug Chicken

Smug Chicken

The daily AI art word game.

Searchle

Searchle

How does google autocomplete this search?

WhereTaken

WhereTaken

Guess the country from a photo.

Retro Snake Game

Retro Snake

Eat the food but don't hit the walls or your own body!