---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 import sqlite3, os, requests from datetime import datetime, timedelta from urllib.parse import urlparse MAIN_DB = \"/home/ben/infra/copecheck/data/copecheck.db\" VIEWS_DB =."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-06-07T23:22:36Z"
site: "main"
source_path: "copecheck/send_weekly_newsletter.py"
---

# !/usr/bin/env python3

Source path: `copecheck/send_weekly_newsletter.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-06-07T23:22:36Z`

```py
#!/usr/bin/env python3
import sqlite3, os, requests
from datetime import datetime, timedelta
from urllib.parse import urlparse

MAIN_DB = "/home/ben/infra/copecheck/data/copecheck.db"
VIEWS_DB = "/home/ben/infra/copecheck/page_views.db"
SITE_URL = "https://copecheck.com"

def get_articles():
    cutoff = (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d')
    conn = sqlite3.connect(MAIN_DB)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    c.execute("SELECT article_slug as slug,source_title as title,source_url,cope_score,COALESCE(analysis_md,'') as summary FROM cope_entries WHERE cope_score>=70 AND created_at>=? ORDER BY cope_score DESC LIMIT 5",(cutoff,))
    high=[dict(r) for r in c.fetchall()]
    c.execute("SELECT article_slug as slug,source_title as title,source_url,cope_score,COALESCE(analysis_md,'') as summary FROM cope_entries WHERE cope_score<=30 AND created_at>=? ORDER BY cope_score ASC LIMIT 5",(cutoff,))
    low=[dict(r) for r in c.fetchall()]
    conn.close()
    read=[]
    try:
        vc=sqlite3.connect(VIEWS_DB); vc.row_factory=sqlite3.Row; vr=vc.cursor()
        vr.execute("SELECT slug,title,url,SUM(view_count) as views FROM page_views WHERE view_date>=? AND url LIKE '/v/%' GROUP BY slug ORDER BY views DESC LIMIT 5",(cutoff,))
        rows=[dict(r) for r in vr.fetchall()]; vc.close()
        c2=sqlite3.connect(MAIN_DB); c2.row_factory=sqlite3.Row; cur=c2.cursor()
        for r in rows:
            cur.execute("SELECT cope_score,COALESCE(analysis_md,'') as summary,source_url FROM cope_entries WHERE article_slug=?",(r['slug'],))
            e=cur.fetchone()
            if e: r.update(dict(e))
            read.append(r)
        c2.close()
    except Exception as ex: print(f"Views error: {ex}")
    return high,low,read

def badge(s):
    if s is None: return ""
    col = "#dc2626" if s>=70 else "#16a34a" if s<=30 else "#6b7280"
    return ('<span style="background:' + col +
            ';color:white;padding:2px 8px;border-radius:3px;font-size:12px;font-weight:bold;">'
            + str(s) + '/100</span>')

def card(a):
    t = a.get('title', 'Untitled'); s = a.get('cope_score')
    sm = (a.get('summary', '') or '')[:180]
    slug = a.get('slug', ''); src = a.get('source_url', ''); views = a.get('views')
    copecheck_url = (SITE_URL + '/v/' + slug) if slug else (src or '#')
    url = copecheck_url
    try: dom = urlparse(src or '').netloc.replace('www.', '')
    except: dom = ''
    vh = (' &middot; <span style="color:#6b7280">' + f'{views:,}' + ' views</span>') if views else ''
    sm_div = ('<div style="color:#555;font-size:14px;line-height:1.5;">' + sm + '</div>') if sm else ''
    dom_div = ('<div style="color:#9ca3af;font-size:12px;">via <a href="' + src + '" style="color:#9ca3af;" target="_blank">' + dom + '</a></div>') if dom and src else (('<div style="color:#9ca3af;font-size:12px;">via ' + dom + '</div>') if dom else '')
    return (
        '<div style="margin-bottom:20px;padding:16px;border-left:3px solid #e5e7eb;background:#fafafa;">'
        '<div style="margin-bottom:6px;">' + badge(s) + vh + '</div>'
        '<div style="font-size:16px;font-weight:600;margin-bottom:6px;">'
        '<a href="' + url + '" style="color:#111;text-decoration:none;">' + t + '</a></div>'
        + sm_div + dom_div +
        '</div>'
    )

def cope_of_week_html(high):
    if not high: return ""
    a = high[0]; t = a.get('title', 'Untitled'); s = a.get('cope_score')
    sm = (a.get('summary', '') or '')[:250]
    slug = a.get('slug', ''); src = a.get('source_url', '')
    copecheck_url = (SITE_URL + '/v/' + slug) if slug else (src or '#')
    url = copecheck_url
    try: dom = urlparse(src or '').netloc.replace('www.', '')
    except: dom = ''
    return (
        '<div style="background:#111;color:white;padding:24px;margin-bottom:32px;border-radius:4px;">'
        '<div style="font-size:11px;letter-spacing:0.2em;text-transform:uppercase;'
        'color:#f87171;margin-bottom:8px;">&#11088; Cope of the Week</div>'
        '<div style="font-size:20px;font-weight:700;margin-bottom:8px;">'
        '<a href="' + url + '" style="color:white;text-decoration:none;">' + t + '</a></div>'
        '<div style="background:#dc2626;display:inline-block;padding:3px 10px;border-radius:3px;'
        'font-size:14px;font-weight:bold;margin-bottom:12px;">' + str(s) + '/100</div>'
        '<div style="font-size:14px;color:#d1d5db;line-height:1.6;">' + sm + '</div>'
        + ('<div style="margin-top:12px;font-size:12px;color:#9ca3af;">via <a href="' + src + '" style="color:#9ca3af;" target="_blank">' + dom + '</a></div>' if src and dom else '')
        + '</div>'
    )

SUBMIT_HTML = (
    '<div style="background:#f9fafb;border:1px solid #e5e7eb;padding:20px;margin-top:32px;border-radius:4px;">'
    '<div style="font-size:16px;font-weight:700;margin-bottom:8px;">&#128236; Got a story to score?</div>'
    '<div style="font-size:14px;color:#555;line-height:1.6;margin-bottom:12px;">'
    "See something that needs the CopeCheck treatment? Send us the URL and we'll run it through the oracle."
    '</div>'
    '<a href="https://copecheck.com/submit" style="display:inline-block;background:#111;color:white;'
    'padding:10px 20px;text-decoration:none;font-size:13px;font-weight:600;border-radius:3px;">'
    'Submit a story &#8594;</a>'
    '<div style="margin-top:12px;font-size:12px;color:#9ca3af;">Or reply directly to this email.</div>'
    '</div>'
)

FOOTER_HTML = (
    '<div style="border-top:1px solid #e5e7eb;margin-top:40px;padding-top:16px;'
    'color:#9ca3af;font-size:12px;text-align:center;">'
    '<a href="https://copecheck.com" style="color:#6b7280;">CopeCheck.com</a> &middot; '
    '<a href="{{{ unsubscribe_url }}}" style="color:#6b7280;">Unsubscribe</a> &middot;'
    '<a href="https://copecheck.com/submit" style="color:#6b7280;">Submit a story</a>'
    '</div>'
)

def build(high, low, read):
    week = datetime.now().strftime('%B %d, %Y')
    total = len(high) + len(low) + len(read)
    hero = cope_of_week_html(high)
    sections = ""
    if high:
        sections += ('<h2 style="color:#dc2626;font-size:18px;border-bottom:2px solid #dc2626;'
                     'padding-bottom:8px;margin-top:32px;">&#128308; Most Cope</h2>'
                     + ''.join(card(a) for a in high))
    if low:
        sections += ('<h2 style="color:#16a34a;font-size:18px;border-bottom:2px solid #16a34a;'
                     'padding-bottom:8px;margin-top:32px;">&#128994; Most Lucid</h2>'
                     + ''.join(card(a) for a in low))
    if read:
        sections += ('<h2 style="color:#2563eb;font-size:18px;border-bottom:2px solid #2563eb;'
                     'padding-bottom:8px;margin-top:32px;">&#128200; Most Read</h2>'
                     + ''.join(card(a) for a in read))
    header = (
        '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'
        '<body style="font-family:-apple-system,sans-serif;max-width:600px;margin:0 auto;padding:20px;color:#111;">'
        '<div style="border-bottom:3px solid #111;padding-bottom:16px;margin-bottom:24px;">'
        '<h1 style="font-size:28px;font-weight:800;margin:0;">The Cope Report</h1>'
        f'<p style="color:#6b7280;margin:4px 0 0 0;">Week of {week} &middot; {total} articles scored</p>'
        '</div>'
        '<p style="font-size:16px;color:#374151;margin-bottom:24px;">'
        "The week's most revealing AI coverage, scored for omission.</p>"
    )
    return header + hero + sections + SUBMIT_HTML + FOOTER_HTML + '</body></html>'

def send_newsletter(html, subject, send_now=False):
[redacted secret-like line]
    aud = os.environ.get("RESEND_AUDIENCE_ID", "")
    frm = os.environ.get("RESEND_FROM", "The Cope Report <newsletter@copecheck.com>")
[redacted secret-like line]
    if not aud: print("ERROR: RESEND_AUDIENCE_ID not set"); return
[redacted secret-like line]
    r = requests.post("https://api.resend.com/broadcasts", headers=h,
                      json={"audience_id": aud, "from": frm, "subject": subject,
                            "html": html, "name": subject}, timeout=30)
    print(f"Create: {r.status_code} {r.text[:200]}")
    if r.status_code not in (200, 201): return
    bid = r.json().get("id"); print(f"Broadcast: {bid}")
    if send_now and bid:
        sr = requests.post(f"https://api.resend.com/broadcasts/{bid}/send",
                           headers=h, json={}, timeout=30)
        print(f"Send: {sr.status_code} {'SUCCESS' if sr.status_code in (200,201) else 'FAILED'}")
    else:
        print(f"Draft at resend.com/broadcasts/{bid}")

if __name__ == "__main__":
    import sys
    send_now = "--send" in sys.argv
    print("Fetching..."); high, low, read = get_articles()
    print(f"Found: {len(high)} cope | {len(low)} lucid | {len(read)} read")
    week = datetime.now().strftime('%B %d, %Y')
    html = build(high, low, read)
[redacted secret-like line]
        open('/tmp/newsletter_preview.html', 'w').write(html); print("Preview saved")
    else:
        send_newsletter(html, f"The Cope Report - Week of {week}", send_now=send_now)
```
