Skip to content

Working With `Torrent` Object

Jacky He edited this page Jun 14, 2026 · 5 revisions

Introduction to torrent

BitTorrent(bt) can track an individual torrent by the torrent file, the magnet link, or the info hash. The magnet link and info hash only provide the identifier(or some additional information as well) while the torrent file contains all the necessary information for validating the downloading file. Which means if a magnet link or info hash was provided, torrent file will be downloaded from other peers. It is possible that no connected peer has the whole copy of the torrent file which the client will not be able to start downloading.

Creating a Torrent object

Currently the lib support adding the torrent through torrent file and info hash. The magnet link support is still under development.

from torrent file

from torrentlib import Torrent

torrent = Torrent.from_file("example.torrent")

from info hash

Create a minimal Torrent when you only have an info hash, for example from a magnet link:

from torrentlib import Torrent, TorrentStatus

torrent = Torrent(
    info_hash="1234567890abcdef1234567890abcdef12345678"
)

by manually constructing the torrent object

from torrentlib import Torrent, TorrentStatus

torrent = Torrent(
    info_hash="1234567890abcdef1234567890abcdef12345678",
    total_size=1145141919810,
    left=1145141919810,
    downloaded=0,
    uploaded=0,
    event=TorrentStatus.STOPPED,
    name="example_file.iso",
    piece_length=None,
    num_pieces=None,
)

Retrieve information from Torrent object

# creating torrent object

print(torrent)
print(torrent.name)
print(torrent.info_hash)
print(torrent.total_size)
print(torrent.piece_length)
print(torrent.num_pieces)

files = torrent.get_files_info() # returns `None` until metadata is available.
if files:
    for file_hash, file_info in files.items():
        print(file_hash, file_info["name"], file_info["length"])

Note

  • Torrent owns runtime swarm state such as downloaded, uploaded, left, event, and peer caches.
  • Torrent.update_from_metadata() verifies that received metadata matches the original info hash.

Clone this wiki locally