python3使用bencode.py库实现BT种子生成磁力链接

需要先安装bencode.py库。

pip install bencode.py
import bencode
import hashlib
from urllib.parse import quote


def torrent_file_to_magnet(torrent_file):
    data =  open(torrent_file, 'rb').read()
    metadata = bencode.bdecode(data)
    name = metadata['info']['name']
    dn = quote(name)
    info_bts = bencode.bencode(metadata['info'])
    info_hash = hashlib.sha1(info_bts).hexdigest()
    return f'magnet:?xt=urn:btih:{info_hash}&dn={dn}'


if __name__ == '__main__':
    print(torrent_file_to_magnet('ubuntu-20.04-desktop-amd64.iso.torrent'))

 

输出:

magnet:?xt=urn:btih:9fc20b9e98ea98b4a35e6223041a5ef94ea27809&dn=ubuntu-20.04-desktop-amd64.iso

  

 

posted @ 2019-04-21 16:23  fatalord  阅读(2608)  评论(0编辑  收藏  举报