Unlocking the Mystery of the Tweet Preview Image

Can anyone help me figure out how to extract a Tweet's preview image from its link? I've been using the html-metadata-parser module to get meta tags, but I'm having trouble finding the image tag for tweets on Twitter. Surprisingly, when I share the link on platforms like Discord, Instagram, and Whatsapp, the tweet's image shows up. How can I extract the preview image link?

 require('dotenv').config();

    const router = require('express').Router();
    const Meta = require('html-metadata-parser');
    const axios = require('axios');
    const Jimp = require('jimp');

    router.post('/webhooks/discounts', async (res, req) => {
    const { link, provider, oauth } = req.body;

    if (
        oauth === process.env.IFTTTOAUTH
    ) {

        var response = await Meta.parser(link);
        const metaTags = JSON.stringify(response, null, 3);

        let hasImage;
        let ProviderNameURL;

        await metaTags.og.images[0] ? hasImage = true : hasImage = false;
        provider === "Steam" ? ProviderNameURL = "steam" : provider === "Ubisoft" ? ProviderNameURL = "ubisoft" : provider === "EpicGames" ? ProviderNameURL = "epic_games" : provider === "GOG.com" ? ProviderNameURL = "gog_com" : provider === "Humble Bundle" ? ProviderNameURL = "humble_bundle" : "unknown";

        const text = await metaTags.og.description;
        const image = hasImage === true ? await metaTags.og.images[0].url : null;
        const icon = `https://cdn.syfac.xyz/images/game_markets/${ProviderNameURL}.png`;
        const urlToDiscount = link;

        try {
            axios.post(requesterURL, {
                text,
                image,
                provider,
                icon,
                urlToDiscount,
                hasImage,
            })
        } catch (err) {
            console.log(err)
        }
    } else {return;}
    })

    module.exports = router;

I'm struggling with extracting the correct image link as the og:image represents the profile picture, not the tweet image.

Upon examining Twitter's meta tags, I noticed links with preconnect and dns-prefetch leading to //pbs.twimg.com. The image source in Discord embeds also point to pbs.twimg.com, which seems promising. However, I'm still unsure how to retrieve the actual tweet image.

Answer №1

It appears that you are in search of the preview image automatically generated for a Tweet. Utilizing the Twitter API is recommended for this task as it proves to be more effective than parsing or scraping data. For more information, please refer to: https://developer.twitter.com/en/docs/twitter-api/data-dictionary/object-model/media

To achieve this, follow these steps:

  • Create a Twitter Developer account to gain access to the Twitter API.
  • Utilize the API to retrieve comprehensive details about Tweets and/or Twitter users.

For instance:

Sample Tweet URL: https://twitter.com/TravelVida/status/1380913486931361794, with the ID: 1380913486931361794.

I employed this ID to formulate a request which was then executed using Postman. Your scenario would involve adapting this call to your JavaScript code. The request URL is as follows:

https://api.twitter.com/2/tweets/:id?expansions=attachments.media_keys&media.fields=duration_ms,height,media_key,preview_image_url,public_metrics,type,url,width

Subsequently, the response received was:

{
    "data": {
        "attachments": {
            "media_keys": [
                "3_1380913484095963145",
                "3_1380913484456718339"
            ]
        },
        "id": "1380913486931361794",
        "text": "Amankila, Bali, Indonesia 🇮🇩\nvia: bennyjurdi 
    },
    "includes": {
        "media": [
            {
                "height": 1537,
                "width": 1242,
                "media_key": "3_1380913484095963145",
                "url": "https://pbs.twimg.com/media/Eyn9f1UWQAkLAFe.jpg",
                "type": "photo"
            },
            {
                "height": 1540,
                "width": 1242,
                "media_key": "3_1380913484456718339",
                "url": "https://pbs.twimg.com/media/Eyn9f2qW8AMbC0-.jpg",
                "type": "photo"
            }
        ]
    }
}

The desired preview URL belongs to the last image. Image URL:

View the Preview:https://i.sstatic.net/Llq97.png

Answer №2

Utilizing this header allows for the retrieval of correct images from various URLs

headers: {
"user-agent": "googlebot", // using googlebot crawler user agent for fetching
"Accept-Language": "fr-CA", // accessing site in French language
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having an issue with Javascript onclick not updating div content upon first click

Having difficulty getting content from one div to another on the initial click. Some of my code: <a href="#" onClick="goPage1();">Feed</a> Function being called: function goPage1(){ $("#feed").html(""); get_jsonp_feed(); $("#con ...

Tips for enforcing validation rules at the class level using Angular's version of jQuery Validate

After utilizing jQuery Validate's convenient addClassRules function to impose a rule on all elements of a specific class, rather than relying on the attributes of their name, I encountered a roadblock when trying to do the same with the Angular wrappe ...

Display the output of a run script within an HTML div element

I am facing a challenge with a button in my HTML file that, when clicked, calls upon the following script: function onShowTest() { $('div#content').html('<script>alert("Hello")</script>'); }; Currently, when I click th ...

Discover the color value within an array that begins with the "#" symbol

In my PHP code, I have written a function that extracts values from a CSS file and creates an array. Now, I need to loop through this array and create another array that only contains color values (strings starting with #). The challenge is that the length ...

List of models loaded in Three.js

Within this block of code, my goal is to load multiple 3D models using the asynchronous .load method. async function loadModels(lights, roomWidth, roomHeight) { // Initializing an empty array to store the loaded models models = [] /* Lo ...

Alert: Jade has detected an unforeseen block called "scripts"

I created a jade file with the following content: extends layout block content h1= title p Hello and welcome to #{title} block scripts script(src='/socket.io/socket.io.js') script(src='/javascripts/client.js') But when I try ...

Using arrow keys and return to effortlessly navigate through text input fields

Currently, I am working on developing a jQuery-based navigation system for switching between multiple input fields. The first part of the code is functioning correctly, allowing users to navigate downwards using either the down arrow or the return key. H ...

Ways to display additional selected values in a select menu

I have a basic form on my website that includes options like: Select 1 and Select 2. I would like to set it up so that if I select value Home in Select 1, the value in Select 2 changes to something like residence. How can I achieve this using a database? ...

Go back to the top by clicking on the image

Can you help me with a quick query? Is it feasible to automatically scroll back to the top after clicking on an image that serves as a reference to jQuery content? For instance, if I select an image in the "Portfolio" section of , I would like to be tak ...

The latest URL is not launching in a separate tab

Looking for some assistance with this code snippet: <b-btn variant="primary" class="btn-sm" :disabled="updatePending || !row.enabled" @click="changeState(row, row.dt ? 'activate' : 'start&apo ...

What is the best way to eliminate all text that appears after the final appearance of a character in JavaScript?

Suppose we have a specific string that looks like this: "A - B - C asdas K - A,B,C" Assume the character delimiter is "-" The goal is to extract everything before the last occurrence of "-", which in this case would be &quo ...

Converting PHP JSON encode to an Ajax array proved to be quite challenging for me at first, as it was a new concept to

Managing Students Data public function retrieveStudentsInformation() { $studentsData = $this->member->getStudentsPosts(); $formattedStudents = array(); for($i=0; $i<count($studentsData); $i++) { $formattedStudents[$i][&a ...

Error encountered in the identify() method of Microsoft Face API

While utilizing Microsoft Face API with project oxford in JavaScript, I encountered an issue when using the "identify" function resulting in an error message of "Invalid request body." client.face.identify({ faces: arrayFaceId, personGroupId: "groupId ...

What is the easiest way to simulate the Ctrl+C key event using jQuery?

I need to programmatically simulate pressing Ctrl+C in order to copy text from a page. My initial attempt looked like this: $('#codetext').click( function() { $("#codetext").trigger({ type: 'keydown', which: 99 }); } Her ...

Is there a definitive way to distinguish between scrollTop and scrollHeight in web development?

For instance, function checkingScroll(){ var newHeight = element.scrollHeight; var scrollTopValue = element.scrollTop; alert("The scrollHeight property is: " + newHeight + "px"); alert("The scrollTop property is: " + scrollTopValue ...

How can I use jQuery to automatically change the background color of each item to match the color of the next

I have a list with 4 items, each item has a specific background color set in the style attribute. <div class="list"> <div style="background: red"></div> <div style="background: blue"></div> <div style="background: gr ...

Exploring the power of chaining collection methods and promises in Node.js HTTP requests

My goal is to extract data from a MongoDB database using the find() method, specifically retrieving documents that have a specified "room" value. From there, I aim to identify all unique values within the array of rooms, based on the key "variety". I initi ...

Difficulty in displaying a set of information through JavaScript

Greetings, I have created a tooltip that can be found at this link: http://jsfiddle.net/QBDGB/83/. In this tooltip, I have defined two "functions" like so: function mousemove1(d) { div .text("data 1: " + d.value + " at " + formatTime(new Date( ...

Even though I have successfully stored a key value pair in LocalStorage using JSON stringify and setItem, the data does not persist after the page is refreshed

I recently developed a Todo application that runs smoothly, except for one crucial issue - the localStorage data does not persist after refreshing the page. Initially, the localStorage operations functioned properly when there were fewer event handlers in ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...