CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-torrentool

A Python library for creating, reading, and modifying torrent files with bencoding utilities and CLI tools.

Overview
Eval results
Files

utilities.mddocs/

Utilities

Helper functions for common torrent-related operations including file size formatting, version information, tracker management, and torrent caching services.

Capabilities

Version Information

Get torrentool version information for torrent metadata.

def get_app_version() -> str:
    """
    Return full version string suitable for Torrent.created_by field.
    
    Combines application name with version number in standard format.
    Automatically used by Torrent.create_from() method.
    
    Returns:
    str: Version string in format "torrentool/X.Y.Z"
    """

File Size Formatting

Convert byte sizes to human-readable format.

def humanize_filesize(bytes_size: int) -> str:
    """
    Convert bytes to human-readable file size format.
    
    Uses binary (1024-based) units: B, KB, MB, GB, TB, PB, EB, ZB, YB.
    Rounds to 2 decimal places for readability.
    
    Parameters:
    - bytes_size (int): Size in bytes
    
    Returns:
    str: Formatted size string (e.g., "1.5 GB", "512 MB", "0 B")
    """

Torrent Caching

Upload torrent files to caching services for immediate sharing.

def upload_to_cache_server(fpath: str) -> str:
    """
    Upload .torrent file to torrage.info cache server.
    
    Provides immediate torrent sharing capability without requiring
    a web server. Returns direct download URL for the cached torrent.
    
    Parameters:
    - fpath (str): Path to .torrent file to upload
    
    Returns:
    str: Direct download URL for the cached torrent file
    
    Raises:
    RemoteUploadError: If upload fails due to network issues or server errors
    ImportError: If 'requests' package is not installed
    """

Tracker List Management

Access curated lists of open (public) BitTorrent trackers.

def get_open_trackers_from_remote() -> List[str]:
    """
    Fetch current list of open tracker URLs from remote repository.
    
    Downloads up-to-date list of public trackers from the torrentool
    GitHub repository. Recommended for getting latest tracker information.
    
    Returns:
    List[str]: List of tracker announce URLs
    
    Raises:
    RemoteDownloadError: If download fails due to network issues
    ImportError: If 'requests' package is not installed
    """

def get_open_trackers_from_local() -> List[str]:
    """
    Get list of open tracker URLs from local backup.
    
    Returns bundled list of public trackers. Used as fallback when
    remote list cannot be retrieved. May be less current than remote list.
    
    Returns:
    List[str]: List of tracker announce URLs from local backup
    """

Usage Examples

Version Information

from torrentool.utils import get_app_version
from torrentool.api import Torrent

# Get version for manual metadata setting
version = get_app_version()
print(f"Using: {version}")  # Output: "torrentool/1.2.0"

# Version is automatically set when creating new torrents
torrent = Torrent.create_from('/path/to/file')
print(f"Created by: {torrent.created_by}")  # Output: "torrentool/1.2.0"

File Size Formatting

from torrentool.utils import humanize_filesize
from torrentool.api import Torrent

# Format file sizes for display
sizes = [0, 512, 1024, 1536, 1048576, 1073741824, 1099511627776]

for size in sizes:
    formatted = humanize_filesize(size)
    print(f"{size:>12} bytes = {formatted}")

# Output:
#            0 bytes = 0 B
#          512 bytes = 512 B
#         1024 bytes = 1.0 KB
#         1536 bytes = 1.5 KB
#      1048576 bytes = 1.0 MB
#   1073741824 bytes = 1.0 GB
# 1099511627776 bytes = 1.0 TB

# Use with torrent file information
torrent = Torrent.from_file('example.torrent')
print(f"Total size: {humanize_filesize(torrent.total_size)}")

for file in torrent.files:
    size_str = humanize_filesize(file.length)
    print(f"{file.name}: {size_str}")

Torrent Caching

from torrentool.utils import upload_to_cache_server
from torrentool.api import Torrent
from torrentool.exceptions import RemoteUploadError

# Create and cache a torrent for immediate sharing
torrent = Torrent.create_from('/path/to/my/files')
torrent.announce_urls = ['udp://tracker.example.com:80/announce']
torrent.to_file('my_files.torrent')

try:
    # Upload to cache server
    cache_url = upload_to_cache_server('my_files.torrent')
    print(f"Torrent cached at: {cache_url}")
    print("Ready for immediate download and sharing!")
    
    # Cache URL can be shared directly with others
    # They can download the .torrent file immediately
    
except RemoteUploadError as e:
    print(f"Upload failed: {e}")
    print("Torrent file saved locally but not cached online")

except ImportError:
    print("Install 'requests' package to use caching: pip install requests")

Tracker Management

from torrentool.utils import get_open_trackers_from_remote, get_open_trackers_from_local
from torrentool.api import Torrent
from torrentool.exceptions import RemoteDownloadError

# Get tracker list for new torrent
try:
    # Try to get latest tracker list from remote
    trackers = get_open_trackers_from_remote()
    print(f"Retrieved {len(trackers)} trackers from remote")
    
except RemoteDownloadError:
    # Fall back to local list if remote fails
    print("Remote download failed, using local tracker list")
    trackers = get_open_trackers_from_local()
    print(f"Using {len(trackers)} local trackers")

except ImportError:
    print("Install 'requests' package for remote trackers: pip install requests")
    trackers = get_open_trackers_from_local()

# Create torrent with tracker list
torrent = Torrent.create_from('/path/to/share')
torrent.announce_urls = trackers[:10]  # Use first 10 trackers
torrent.comment = 'Torrent with public trackers'
torrent.to_file('public_torrent.torrent')

print("Torrent created with public trackers:")
for i, tracker in enumerate(torrent.announce_urls[0][:5]):  # Show first 5
    print(f"  {i+1}. {tracker}")

Combining Utilities

from torrentool.api import Torrent
from torrentool.utils import (
    get_open_trackers_from_remote, 
    get_open_trackers_from_local,
    upload_to_cache_server,
    humanize_filesize
)
from torrentool.exceptions import RemoteDownloadError, RemoteUploadError

def create_and_share_torrent(path, comment=None, cache=True):
    """Complete workflow for creating and sharing a torrent."""
    
    # Create torrent
    print(f"Creating torrent from: {path}")
    torrent = Torrent.create_from(path)
    
    # Add metadata
    if comment:
        torrent.comment = comment
    
    # Get tracker list
    try:
        trackers = get_open_trackers_from_remote()
        print(f"Added {len(trackers)} remote trackers")
    except (RemoteDownloadError, ImportError):
        trackers = get_open_trackers_from_local()
        print(f"Added {len(trackers)} local trackers")
    
    torrent.announce_urls = trackers
    
    # Save torrent
    filename = f"{torrent.name}.torrent"
    torrent.to_file(filename)
    
    # Display info
    size_str = humanize_filesize(torrent.total_size)
    print(f"Torrent created: {filename}")
    print(f"Name: {torrent.name}")
    print(f"Size: {size_str}")
    print(f"Hash: {torrent.info_hash}")
    print(f"Files: {len(torrent.files)}")
    
    # Optional caching
    if cache:
        try:
            cache_url = upload_to_cache_server(filename)
            print(f"Cached at: {cache_url}")
            return filename, cache_url
        except (RemoteUploadError, ImportError) as e:
            print(f"Caching failed: {e}")
    
    return filename, None

# Usage
torrent_file, cache_url = create_and_share_torrent(
    '/path/to/my/collection',
    comment='My awesome collection',
    cache=True
)

Dependencies

Most utility functions have optional dependencies:

  • requests: Required for upload_to_cache_server() and get_open_trackers_from_remote()
  • Installation: pip install requests or pip install torrentool[cli]

Functions gracefully handle missing dependencies by raising ImportError with helpful messages.

Install with Tessl CLI

npx tessl i tessl/pypi-torrentool

docs

bencoding.md

index.md

torrent-operations.md

utilities.md

tile.json