Skip to content

Instantly share code, notes, and snippets.

@zeroxia
Created February 7, 2017 13:44
Show Gist options
  • Save zeroxia/fe06d36280622ed5920d42b2fb0eca3f to your computer and use it in GitHub Desktop.
Save zeroxia/fe06d36280622ed5920d42b2fb0eca3f to your computer and use it in GitHub Desktop.
Convert a .torrent seed file into a magnet:? magnetic link for easier batch import into some offline downloading service
#!/usr/bin/python
# vim: set fileencoding=utf-8:
# Code shamelessly copied from:
# http://stackoverflow.com/questions/12479570/given-a-torrent-file-how-do-i-generate-a-magnet-link-in-python
# How to install the `bencode' module for Python on Windows:
# Run a command line window as Administrator:
# % python -m pip install bencode
import sys
import bencode
import hashlib
import base64
import urllib
if len(sys.argv) != 2:
print "Must provide one argument"
sys.exit(1)
torrent = open(sys.argv[1], 'rb').read()
metadata = bencode.bdecode(torrent)
hashcontents = bencode.bencode(metadata['info'])
digest = hashlib.sha1(hashcontents).digest()
b32hash = base64.b32encode(digest)
params = {'xt': 'urn:btih:%s' % b32hash,
'dn': metadata['info']['name'],
'tr': metadata['announce'] }
# 'xl': metadata['info']['length'] }
paramstr = urllib.urlencode(params)
magneturi = 'magnet:?%s' % paramstr
print magneturi
@zeroxia
Copy link
Author

zeroxia commented Feb 7, 2017

Successfully tested using:
Python 2.7.11
Windows 10 Version 1607 (OS Build 14393.693)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment