Converting a Magnet Link into a Torrent

UPDATE – 2012-04-30 – User Faless on GitHub has added a good bit of functionality. Check it out.

For some reason, my version of the rtorrent client on ubuntu does not open magnet files. So, I wanted to see if there was a way to create torrent files from magnet files. I couldn’t find a good example, so I wrote my own.

This will convert a magnet link into a .torrent file:

First, make sure your system has Python and the Python Library:

sudo apt-get install python-libtorrent

Then, you can run the following code by calling this command:



Created on Apr 19, 2012
@author: dan
if __name__ == '__main__':
    import libtorrent as lt
    import time
    TorrentFilePath = "/home/dan/torrentfiles/" + str(time.time()) + "/"
    TorrentFilePath2 = "/home/dan/torrentfiles/" + str(time.time()) + "/" + str(time.time()) + ".torrent"
    ses = lt.session()
    #ses.listen_on(6881, 6891)
    params = {
        'save_path': TorrentFilePath,
        'duplicate_is_error': True}
    link = "magnet:?xt=urn:btih:599e3fb0433505f27d35efbe398225869a2a89a9&dn=ubuntu-10.04.4-server-i386.iso&"
    handle = lt.add_magnet_uri(ses, link, params)
#    ses.start_dht()
    print 'saving torrent file here : ' + TorrentFilePath2 + " ..."
    while (not handle.has_metadata()):
    torinfo = handle.get_torrent_info()
    fs = lt.file_storage()
    for file in torinfo.files():
    torfile = lt.create_torrent(fs)
    f = open(TorrentFilePath2 + "torrentfile.torrent", "wb")
    print 'saved and closing...'
#Uncomment to Download the Torrent:
#    print 'starting torrent download...'
#    while (handle.status().state != lt.torrent_status.seeding):
#        s = handle.status()
#        time.sleep(55)
#        print 'downloading...'

This will create a folder inside of ‘/home/dan/torrentfiles/’ with a structure like:


I added this to GitHub if you want to Fork it.



7 thoughts on “Converting a Magnet Link into a Torrent”

  1. I have error run the script :

    Traceback (most recent call last):
    File “”, line 22, in
    handle = lt.add_magnet_uri(ses, link, params)
    KeyError: ‘storage_mode’

  2. Thanks for this, can be very useful. Sadly at the moment it doesn’t work on Debian stable. I guess I need a newer python-libtorrent, got this error:

    Traceback (most recent call last):
    File “”, line 59, in
    handle = lt.add_magnet_uri(ses, magnet, params)
    KeyError: ‘storage_mode’

    So I fired up vnc, for now!

    thanks anyway 🙂 maybe it was my error I don’t know

  3. I also got KeyError: ‘storage_mode’ error.
    using version:
    python-libtorrent/natty uptodate 0.15.5-1
    and the github version of the script.

    I fixed it by setting editing “params” to be:

    params = {
    ‘storage_mode’: lt.storage_mode_t.storage_mode_sparse,
    ‘paused’: False,
    ‘auto_managed’: True,
    ‘save_path’: tempdir,
    ‘duplicate_is_error’: True

    which provides the extra things it seems to be expecting.

Comments are closed.