How to tweet images using the v2 Twitter API

Tweet images using v2 API

In this tutorial, I will show you how to tweet out an image using the v2 Twitter API.

This tutorial follows on from Creating a Twitter bot with Node.js and Twitter API, I recommend going through that first to get set up sending a simple tweet.

Table of contents

Step 1: Install required packages

We will need a couple more packages for tweeting images. Go ahead and run the following

npm install fs
npm install request

The first package is so we can interact with the file system and the second in for making requests.

Step 2: Create a utilities.js file and add the download() function

When we want to tweet an image, we first have to upload the image to the Twitter servers. When we do that, it will return a mediaId, which we can then use when creating a tweet with an image.

If the images you will be tweeting are in the same file system, then you can skip the following. If they are hosted on a third party platform e.g. Imgur, then you will need to first download it, upload it to the Twitter servers, then use the mediaId it sends back to tweet the image.

Follow the steps below to download the image onto the file system.

Go ahead and create a utilities.js and paste the following code

utilities.js
const request = require("request");
const fs = require("fs");

const download = function (uri, filename, callback) {
  request.head(uri, function (err, res, body) {
    request(uri).pipe(fs.createWriteStream(filename)).on("close", callback);
  });
};

module.exports = { download };

Step 3: Upload the image to Twitter and tweet it

Let's go ahead and call the download function so we can download the image on the local file system, then upload the image to Twitter, and finally tweet out the image.

In this example, I have an image of Ukraine hosted on Imgur I am using.

Add the following to your index.js file

index.js
const { download } = require("./utilities");

const tweet = async () => {

    const uri = "https://i.imgur.com/Zl2GLjnh.jpg";
    const filename = "image.png";

    download(uri, filename, async function(){
        try {
            const mediaId = await twitterClient.v1.uploadMedia("./image.png");
            await twitterClient.v2.tweet({
                text: "Hello world! This is an image in Ukraine!",
                media: {
                    media_ids: [mediaId]
                }
            });
        } catch (e) {
            console.log(e)
        }
    });
}

Your final index.js file will look like this

index.js
require("dotenv").config({ path: __dirname + "/.env" });
const { twitterClient } = require("./twitterClient.js");
const CronJob = require("cron").CronJob;
const express = require('express')
const app = express()
const port = process.env.PORT || 4000;
const { download } = require("./utilities");

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})

const tweet = async () => {

    const uri = "https://i.imgur.com/Zl2GLjnh.jpg";
    const filename = "image.png";

    download(uri, filename, async function(){
        try {
            const mediaId = await twitterClient.v1.uploadMedia("./image.png");
            await twitterClient.v2.tweet({
                text: "Hello world! This is an image in Ukraine!",
                media: {
                    media_ids: [mediaId]
                }
            });
        } catch (e) {
            console.log(e)
        }
    });
}

const cronTweet = new CronJob("*/30 * * * * *", async () => {
    tweet();
});
  
cronTweet.start();

You can now go ahead an run the node.js application and it will tweet out your message plus your image.


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!