DEV Community

Siftwright
Siftwright

Posted on Originally published at siftwright.com

Why your link preview is blank on Slack, LinkedIn or X: check og:image with ~80 lines of Python

You paste a link into Slack, LinkedIn or X and get a bare URL, a tiny square icon, or the wrong picture. The cause is nearly always one of a handful of things in the page's <head> or in the share image itself. Here's a small checker in standard-library Python that finds them, plus what it reported on a few real sites today.

What link previews actually read

When you share a URL, the platform's crawler (facebookexternalhit, Twitterbot, LinkedInBot, Slackbot, Discordbot) fetches the page and looks for:

  • Open Graph tags: og:title, og:description, og:image (and og:url). Almost every platform uses these.
  • twitter:card: X uses it to choose between a small card (summary) and a big image card (summary_large_image). If it's missing, you get the small card or none.
  • The image itself: it must be reachable without cookies, served as image/*, and big enough. The common recommendation for large cards is 1200x630 (about 1.91:1). X documents a 5 MB limit for card images.
  • robots.txt: if the page disallows a preview crawler that respects robots.txt, that platform can't read the tags at all.

The checker (~80 lines, no dependencies)

It fetches the page, parses the og: and twitter: meta tags with html.parser, downloads only the first 64 KB of the image (enough to read PNG, GIF, WebP and JPEG dimensions from the header), and asks urllib.robotparser whether five preview crawlers may fetch the URL.

import sys, struct, urllib.request, urllib.robotparser
from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit

BOTS = ["facebookexternalhit", "Twitterbot", "LinkedInBot", "Slackbot", "Discordbot"]

UA = "Mozilla/5.0 (compatible; preview-check/1.0)"

class Meta(HTMLParser):
    def __init__(self):
        super().__init__(); self.tags = {}; self.title = None; self._t = False
    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "meta":
            key = a.get("property") or a.get("name")
            if key and a.get("content") and key.lower().startswith(("og:", "twitter:")):
                self.tags.setdefault(key.lower(), a["content"].strip())
        elif tag == "title": self._t = True
    def handle_data(self, d):
        if self._t and self.title is None: self.title = d.strip()
    def handle_endtag(self, tag):
        if tag == "title": self._t = False

def get(url, limit):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=15) as r:
        return r.geturl(), r.headers, r.read(limit)

def image_size(b):
    if b[:8] == b"\x89PNG\r\n\x1a\n": return struct.unpack(">II", b[16:24])
    if b[:6] in (b"GIF87a", b"GIF89a"): return struct.unpack("<HH", b[6:10])
    if b[:4] == b"RIFF" and b[8:12] == b"WEBP":
        if b[12:16] == b"VP8X": return (int.from_bytes(b[24:27], "little") + 1, int.from_bytes(b[27:30], "little") + 1)
        if b[12:16] == b"VP8 ": w, h = struct.unpack("<HH", b[26:30]); return (w & 0x3fff, h & 0x3fff)
    if b[:2] == b"\xff\xd8":
        i = 2
        while i + 9 < len(b):
            if b[i] != 0xFF: i += 1; continue
            m = b[i + 1]
            if m in (0xC0, 0xC1, 0xC2):
                h, w = struct.unpack(">HH", b[i + 5:i + 9]); return (w, h)
            i += 2 + struct.unpack(">H", b[i + 2:i + 4])[0]
    return None

def check(url):
    final, _, html = get(url, 2_000_000)
    p = Meta(); p.feed(html.decode("utf-8", "replace"))
    t = p.tags; problems = []
    for k in ("og:title", "og:description", "og:image"):
        if k not in t: problems.append(f"missing {k}")
    if "twitter:card" not in t: problems.append("missing twitter:card (X falls back to a small card)")
    img = t.get("og:image") or t.get("twitter:image")
    if img:
        if not img.startswith(("http://", "https://")):
            problems.append(f"og:image is relative ({img}); some scrapers won't resolve it")
        img = urljoin(final, img)
        try:
            _, h, head = get(img, 65536)
            ctype = h.get("Content-Type", "")
            size = image_size(head)
            length = int(h.get("Content-Length") or 0)
            if not ctype.startswith("image/"): problems.append(f"og:image Content-Type is {ctype!r}")
            if size and (size[0] < 600 or size[1] < 315): problems.append(f"og:image is {size[0]}x{size[1]}; large cards want >= 1200x630")
            if length > 5_000_000: problems.append(f"og:image is {length/1e6:.1f} MB; X rejects > 5 MB")
            print(f"  image: {img}\n         {ctype}, {size and '%dx%d' % size}, {length or '?'} bytes")
        except Exception as e:
            problems.append(f"og:image not fetchable: {e}")
    root = "{0.scheme}://{0.netloc}".format(urlsplit(final))
    rp = urllib.robotparser.RobotFileParser(root + "/robots.txt")
    try:
        rp.read()
        for bot in BOTS:
            if not rp.can_fetch(bot, final): problems.append(f"robots.txt blocks {bot}")
    except Exception:
        pass
    print(f"  title: {t.get('og:title') or p.title!r}")
    print("  OK" if not problems else "  " + "\n  ".join("- " + x for x in problems))

for u in sys.argv[1:]:
    print(u)
    try: check(u)
    except Exception as e: print("  ERROR", e)
Enter fullscreen mode Exit fullscreen mode

Run it with any number of URLs:

python3 preview_check.py https://stripe.com https://www.python.org https://example.com
Enter fullscreen mode Exit fullscreen mode

What it found on real sites (run on 28 Nov 2026)

https://stripe.com
  image: https://b.stripecdn.com/mkt-ssr-statics/assets/_next/static/media/stripe.37119086.jpg
         image/jpeg, 2048x1024, 312818 bytes
  title: 'Stripe | Financial Infrastructure to Grow Your Revenue'
  OK
https://www.python.org
  image: https://www.python.org/static/opengraph-icon-200x200.png
         image/png, 200x200, 7821 bytes
  title: 'Welcome to Python.org'
  - missing twitter:card (X falls back to a small card)
  - og:image is 200x200; large cards want >= 1200x630
https://news.ycombinator.com
  title: 'Hacker News'
  - missing og:title
  - missing og:description
  - missing og:image
  - missing twitter:card (X falls back to a small card)
https://example.com
  title: 'Example Domain'
  - missing og:title
  - missing og:description
  - missing og:image
  - missing twitter:card (X falls back to a small card)
https://www.bbc.com/news
  image: https://ichef.bbci.co.uk/images/ic/raw/p0pk35zn.jpg
         image/jpeg, 1920x1080, 21153 bytes
  title: 'BBC News - Breaking news, video and the latest top stories from the U.S. and around the world'
  OK
https://www.linkedin.com
  title: 'LinkedIn: Log In or Sign Up'
  - missing og:image
  - robots.txt blocks Twitterbot
  - robots.txt blocks Slackbot
  - robots.txt blocks Discordbot
https://www.nytimes.com
  ERROR HTTP Error 403: Forbidden
Enter fullscreen mode Exit fullscreen mode

What this shows:

  • stripe.com, bbc.com/news: complete tags and a large image. These unfurl as big cards.
  • python.org: has og:image, but it's a 200x200 icon and there's no twitter:card, so it shows as a small thumbnail card, not a big image.
  • news.ycombinator.com, example.com: no Open Graph tags at all. Platforms fall back to the <title> or show a bare link.
  • linkedin.com: no og:image on the logged-out home page, and its robots.txt disallows the generic user agent, which the parser applies to Twitterbot, Slackbot and Discordbot.
  • nytimes.com: returned 403 to this script. A site can treat a plain script differently from a real preview crawler, so a block here doesn't prove a preview will fail; it just means you need to test with the crawler's own user agent or the platform's debugger.

The usual fixes

  1. Use an absolute og:image URL (https://example.com/og.png, not /og.png). Some crawlers don't resolve relative URLs.
  2. Make the image 1200x630, PNG or JPEG, well under 5 MB, served with an image/png or image/jpeg Content-Type.
  3. Add <meta name="twitter:card" content="summary_large_image"> if you want the big card on X.
  4. Don't put the image behind auth, a cookie wall or a bot challenge. Crawlers don't run JavaScript or click consent banners.
  5. Put the tags in the server-rendered HTML. Tags injected by client-side JavaScript are invisible to most preview crawlers.
  6. Check robots.txt for rules that catch the preview bots (a blanket Disallow: / for User-agent: * does).
  7. Re-scrape after fixing. Platforms cache previews; Facebook's Sharing Debugger and LinkedIn's Post Inspector force a refresh.

Limits of this script

  • It reads the first 2 MB of HTML and the first 64 KB of the image; a JPEG with a very large EXIF block before its size marker can come back without dimensions.
  • It doesn't render JavaScript, which matches most preview crawlers but means it can't tell you what a browser sees.
  • robotparser follows the standard rules; each platform's real crawler behaviour can differ.
  • It doesn't emulate each platform's crop or card layout.

No-code version

If you just want to check one URL, the free Link Preview Checker does the same checks in the browser (Open Graph, twitter:card, image type and size, robots.txt for the preview bots) and shows how the card should look on X, LinkedIn, Facebook, Slack, Discord and WhatsApp. No signup.

If you'd rather build a share image from a page, the free website screenshot tool captures any URL as a PNG.

Top comments (1)

Collapse
 
penny24x7 profile image
Penny •

Useful script. Two gaps I ran into while building a similar check:

  1. The robots check only tests the page URL. robots.txt can allow the page and still block the image path (e.g. Disallow: /img/ under User-agent: Twitterbot), so the tags look perfect and the card stays empty. If the og:image lives on a CDN host, that host has its own robots.txt too. Running can_fetch(bot, img) against the image's own origin catches both.

  2. X has no re-scrape tool like Facebook's debugger or LinkedIn's inspector anymore. It caches the card per exact URL (about 7 days per X's docs), so after a fix the same link can stay blank. Sharing it with a throwaway query like ?v=2 gets a fresh crawl.