discord-archive

A defensive, idempotent, low-frequency command-line tool designed for slow, long-term archival of Discord Direct Messages (DMs) and Group DMs into a local SQLite database.

Features · Requirements · Getting started · Configuration · Usage · Architecture · Development · Documentation · Credits · License

Features

  • Archive direct and group messages to SQLite with resumable checkpoints.
  • Download attachments separately and verify archive integrity.
  • Run bounded jobs manually or with systemd timers.

Requirements

  • Linux workstation or server
  • Python 3.10+ (tested on Python 3.14)
  • Virtual environment (venv)

Getting started

python3 -m venv .venv
source .venv/bin/activate
pip install -e .
discord-archive init
discord-archive status

These local commands initialize the archive and show its status. Configure a token before discovering channels or fetching messages.

Configuration

Your Discord account token must never be committed to Git or stored in public logs. You can configure it via:

  1. Environment variable:

    export DISCORD_TOKEN="your_token_here"
    
  2. Restricted secret file (0600):

    mkdir -p ~/.config/discord-archive
    install -m 0600 /dev/null ~/.config/discord-archive/token
    echo -n "your_token_here" > ~/.config/discord-archive/token
    discord-archive --token-file ~/.config/discord-archive/token discover
    

    Pass --token-file before the subcommand whenever using this file; it is not loaded automatically.

  3. Project .env file (automatically ignored by .gitignore):

    echo 'DISCORD_TOKEN=your_token_here' > .env
    chmod 600 .env
    

(All log outputs automatically redact user tokens and secrets.)

Usage

The tool is accessible via discord-archive (inside the virtualenv) or python3 -m discord_archive.cli.

Initialize database

Creates tables, pragmas, and indexes in discord-archive.sqlite:

discord-archive init

Discover DM channels

Connects to Discord and lists all available 1-on-1 DMs and Group DMs:

discord-archive discover

Run batch crawl

Executes a controlled, limited amount of work and exits cleanly:

# Fetch up to 10 batches (up to 1,000 messages total) across pending channels
discord-archive run --max-batches 10

# Fetch a single specific channel (up to 5 batches)
discord-archive run --channel 123456789012345678 --max-batches 5

# Limit total API requests and adjust pacing delay
discord-archive run --max-requests 20 --batch-delay 3.0

# Dry-run mode (simulates without modifying database)
discord-archive run --dry-run

Catch up new messages (forward sync)

Fetches all messages that were sent or received after the initial archival started (using after={newest_fetched_id}):

# Catch up all channels with new incoming messages
discord-archive catchup

# Catch up a single specific channel
discord-archive catchup --channel 123456789012345678

# Catch up with limits or dry-run
discord-archive catchup --max-batches 10 --batch-delay 2.0

View status and progress

Displays an overview of channel completeness, local message counts, date ranges, and errors:

discord-archive status

Download attachments

Downloads pending message attachments into attachments/<channel_id>/<attachment_id>_<filename>:

# Download up to 20 files per run
discord-archive attachments --max-files 20

# Download attachments for a single channel
discord-archive attachments --channel 123456789012345678 --max-files 50

Note on Expired Discord CDN Links: Discord attachment links expire after 24 hours. The downloader automatically detects HTTP 404/403 responses and calls Discord's POST /api/v10/attachments/refresh-urls endpoint to obtain refreshed URLs with valid signatures.

Verify archive integrity

Performs SQLite foreign key checks, orphan record validation, cursor consistency, and chronology checks:

discord-archive verify

Automation with systemd

Rather than keeping a daemon running 24/7, discord-archive is designed to be invoked periodically (e.g., several times daily) via user systemd units:

  1. Copy service and timer definitions:

    mkdir -p ~/.config/systemd/user
    cp systemd/discord-archive.service ~/.config/systemd/user/
    cp systemd/discord-archive.timer ~/.config/systemd/user/
    
  2. Reload and enable timer:

    systemctl --user daemon-reload
    systemctl --user enable --now discord-archive.timer
    
  3. Check status and logs:

    systemctl --user list-timers
    journalctl --user -u discord-archive.service -n 50
    

Architecture

Archival pipeline

Decoupled crawling and asset pipeline

The extraction pipeline is separated into distinct, isolated components:

  1. Discord Crawler & Archiver: Slowly reads Discord API history and writes to a lossless, relational SQLite database.
  2. Attachment Downloader: Downloads binary assets independently at controlled intervals, supporting Discord CDN expiring URL refresh.

Defensive requests and backoff

In accordance with zero-spoofing principles:

  • No Fingerprint Spoofing & No Client Masquerading: Requests use clean, standard HTTP client headers with transparent User-Agent. No imitation of official Discord desktop or web clients.
  • No Randomized "Human-like" Behavior: Randomization is not used as an evasion tactic.
  • Strict API Protection & Defensive Backoff:
    • Single-threaded, zero concurrency.
    • Paced batch requests (default 2.0s delay between batches).
    • Strict compliance with HTTP 429 rate limits and Retry-After headers.
    • Exponential backoff on server errors (5xx) and network timeouts.
    • Immediate Termination on Security Challenges: If Discord responds with 401 Unauthorized, 403 Forbidden, CAPTCHA, or verification checkpoints, the process halts immediately with a non-zero exit code to require manual inspection.

Lossless data storage (raw_json)

Every entity stored in SQLite (channels, messages, users, attachments, reactions, embeds) stores both relational columns for convenient querying and filtering, and full original raw_json payloads. This guarantees that unmapped fields, future Discord payload changes, or specialized embed/reaction attributes are never lost.

Atomic checkpointing and idempotency

  • Each batch of messages (up to 100 per API request) is committed in a single SQLite transaction (BEGIN IMMEDIATE).
  • The transaction writes/updates users, messages, attachments, embeds, and reactions, while advancing the channel's oldest_fetched_id cursor.
  • If a crash, network error, or rate limit occurs mid-batch, the transaction rolls back, leaving the database and cursor in an uncorrupted state.
  • The crawler can be safely interrupted at any second (Ctrl+C, SIGTERM) and resumed without losing data or creating duplicate records.

Database schema

The database utilizes SQLite with WAL mode enabled and foreign keys enforced.

  • channels: Stores DM and Group DM metadata, recipients list, current pagination cursor (oldest_fetched_id), completion flag (complete = 1), and raw_json.
  • messages: Primary key message_id (Discord Snowflake). Stores author, timestamp, content, edit timestamps, reply references (reply_to_id), and raw_json.
  • users: Discord user profiles (username, global display name, legacy discriminator, avatar hash, and raw_json).
  • attachments: Metadata for message files (filename, content type, size, CDN URLs, local storage path, and download status).
  • reactions: Emoji reactions per message, counts, and animated flags.
  • embeds: Message embeds and rich media previews.
  • crawl_runs: Historical log of every execution, batches fetched, request counts, rate limit encounters, and exit reasons.

Development

Install test dependencies in the activated virtual environment:

pip install -e ".[dev]"

Run the automated test suite with pytest:

.venv/bin/pytest tests/ -v

Documentation

README style guide.

Credits

This project is an independent Python 3 implementation. It contains no direct source code from Tyrrrz/DiscordChatExporter (which is written in C# / .NET).

However, this tool was conceptually inspired by DiscordChatExporter's approach to interacting with the Discord REST API, specifically:

  • Querying Discord REST API v10 endpoints (e.g. GET /users/@me/channels for discovery and GET /channels/{id}/messages for reverse-chronological pagination).
  • Discord snowflake parsing and timestamp extraction mechanisms.
  • Understanding and honoring rate limit headers (Retry-After, X-RateLimit-Reset-After).

This project—including its architectural design, Python source code, test suite, and documentation—was predominantly developed with the assistance of an AI coding agent (Google DeepMind Antigravity) in collaboration with the repository owner.

License

No project-level license file is currently included in this repository. Third-party components retain their own licenses.

S
Description
No description provided
Readme 72 KiB
Languages
Python 100%