Exemplo n.º 1
0
def clear(update: Update, context: CallbackContext) -> None:
	"""
	Limpia los torrents finalizados de la cola de descarga
	"""
	FINISHED_STATES = [
		'uploading',
		'pausedUP',
		'stalledUP',
		'queuedUP',
	]
	if int(update.effective_chat.id) not in config.ALLOWED_IDS:
		not_allowed(update)
	else:
		logger.info(' Un usuario CON permiso ha ejecutado /clear')
		qb = Client(config.TORRENT['server'])
		qb.login(config.TORRENT['user'], config.TORRENT['pass'])
		torrents = qb.torrents()
		del_torrents = len(torrents)
		for torrent in torrents:
			if torrent['state'] in FINISHED_STATES:
				qb.delete(torrent['hash'])
		torrents = qb.torrents()
		del_torrents = del_torrents - len(torrents)
		qb.logout()
		logger.info('{} torrents han sido eliminados de la cola'.format(del_torrents))
		if del_torrents != 0:
			update.message.reply_text('Borrados todos los torrents finalizados')
		else:
			update.message.reply_text('No se ha eliminado ningún torrent de la cola')
class QClientManager(object):
    def __init__(self, url='http://127.0.0.1:8080/', user='', passwd=''):
        self.name = self.__class__.__name__

        # Default Parameters for QClient Session
        self.defautl_url = url
        self.user = user
        self.passwd = passwd

        # Launching Session in QClient
        self.session = Client(self.defautl_url)
        if self.user != '' and self.passwd != '':
            self.session.login(self.user, self.passwd)

    def session_shutdown(self):
        try:
            self.session.shutdown()
        except Exception as e:
            print(e)
        return True

    def get_torrent_info(self):
        torrents = self.session.torrents()
        for torrent_item in torrents:
            print('%s: [%s] \n\t\t- %s' %
                  (self.name, torrent_item['hash'], torrent_item['name']))

    def load_magnet(self, magnet_uri):
        try:
            self.session.download_from_link(magnet_uri)
        except Exception as e:
            print(e)
        return True
Exemplo n.º 3
0
class qbit:
    def __init__(self, login, config):
        self.config = config
        self.login = login
        self.localhost = self.config["host"]
        self.download_path = os.path.expanduser("~") + config["download_path"]
        self.qb = Client(self.localhost)
        self.qb.login(self.config["username"], self.config["passwd"])

    def download(self, download_link):
        if not os.path.exists(self.download_path):
            os.mkdir(self.download_path)
        self.qb.download_from_file(self.login.session.get(
            download_link,
            headers=self.login.headers,
            cookies=self.login.cookies).content,
                                   savepath=self.download_path)

    def download_list(self, download_linklist):
        for download_link in download_linklist:
            self.download(download_link)

    def delete(self):
        torrents = self.qb.torrents()
        torrents_delete_hash = []
        for torrent in torrents:
            exist_days = (time.time() - torrent["added_on"]) / 24 * 1024
            if exist_days > 3 & torrent["uploaded"] / (torrent["total_size"] *
                                                       exist_days) < 0.2:
                torrents_delete_hash.append(torrent["hash"])
        self.qb.delete_permanently(torrents_delete_hash)
Exemplo n.º 4
0
def descargar(link):
    #aqui poner puerto 8080 o el puerto definido en qbit torrent
    cliente = Client("http://127.0.0.1:4000/")
    cliente.login("admin", "adminadmin")
    #en savepath poner donde quiere guardar las peliculas
    cliente.download_from_link(
        link, savepath="/home/jaime/compartida/codigo/downloader/descargas/")
Exemplo n.º 5
0
def thread_torr(name):
    log.append("Поток запущен, бот работает")
    while True:
        if threadStop:
            # bot.stop_polling()
            log.append("Бот остановлен: поток")
            break
        try:
            cont = False
            qb = Client('http://localhost:8080/')
            qb.login('admin', '1karina1')
            torrents = qb.torrents(filter='downloading')
            for dtor in downloadTorrents:
                for tor in torrents:
                    if tor['name'] == dtor['name']:
                        cont = True
                        break
                if cont:
                    cont = False
                    continue
                bot.send_message(dtor['userid'],
                                 "Файл " + dtor['name'] + "загружен")

            qb.logout()
            time.sleep(20)

        except Exception as e:
            print(e)
            log.append("Ошбика")
            time.sleep(3)
Exemplo n.º 6
0
class QBittorrentClient(TorrentClient):
    def __init__(self, endpoint, username, password):
        self._api_client = Client(endpoint)
        self._api_client.login(username, password)
        if not self._api_client:
            message = "Unable to connect to qBittorrent API. Please check your -e, -u and -p arguments."
            logger.error(message)
            raise Exception(message)

    def get_torrent_info(self, torrent_hash):
        torrents = self._api_client.torrents()

        for torrent in torrents:
            if torrent['hash'] == torrent_hash:
                return Torrent(torrent_hash, torrent['progress'] == 1, torrent['category'], torrent['save_path'])

        return None

    def remove_torrent(self, torrent_hash):
        self._api_client.delete_permanently(torrent_hash)

    def stop_torrent(self, torrent_hash):
        self._api_client.pause(torrent_hash)

    def get_torrent_files(self, torrent_hash):
        files = self._api_client.get_torrent_files(torrent_hash)
        parsed_files = []
        for file in files:
            if ".unwanted" not in file['name']:
                parsed_files.append(TorrentFile(file['name']))

        return parsed_files
Exemplo n.º 7
0
def pQbClient():
    from qbittorrent import Client
    info = getQbConf()
    url = 'http://' + info['QB_HOST'] + ':' + info['QB_PORT'] + '/'
    qb = Client(url)
    qb.login(info['QB_USER'], info['QB_PWD'])
    return qb
Exemplo n.º 8
0
def status(update: Update, context: CallbackContext) -> None:
	"""
	Muestra el estado de la cola de descargas
	"""
	if int(update.effective_chat.id) not in config.ALLOWED_IDS:
		not_allowed(update)
	else:
		logger.info(' El usuario ha ejecutado /status')
		qb = Client(config.TORRENT['server'])
		qb.login(config.TORRENT['user'], config.TORRENT['pass'])
		torrents = qb.torrents()
		qb.logout()
		if len(torrents) == 0:
			update.message.reply_text('Parece que en este momento no hay nada en cola')
		else:
			update.message.reply_text('Hay {} torrents en cola\n'.format(len(torrents)))
			for torrent in torrents:
				update.message.reply_text(
					'Torrent: {}\nEstado: {}\nTamaño: {}\nProgreso: {}%\nTasa de descarga: {}/s\n'.format(
						torrent['name'],
						torrent['state'],
						get_size_format(torrent['total_size']),
						str(float(torrent['progress'])*100),
						get_size_format(torrent['dlspeed']),
						)
					)
Exemplo n.º 9
0
def torrent_view(request):
    qb = Client('http://127.0.0.1:8080/')
    qb.login('admin', 'adminadmin')
    BASE_DIR = Path(__file__).resolve().parent.parent
    d_path = os.path.join(BASE_DIR, 'static/folder/')
    print("Location : ", qb.get_default_save_path())
    if request.method == 'POST':
        ezflix = Ezflix(query=request.POST['title1'],
                        media_type='movie',
                        quality='720p',
                        limit=1)
        shows = ezflix.search()
        # magnet = 'https://webtorrent.io/torrents/big-buck-bunny.torrent'
        magnet = 'https://webtorrent.io/torrents/cosmos-laundromat.torrent'
        if shows is not None:
            for s in shows:
                if s['imdb'] == request.POST['imdb1']:
                    print(s['link'])
                    # torrent_location=Torrent.objects.filter(Info_code=s['title'])[0]
                    # print ("Finally",torrent_location.title)
                    # print(torrent_location)
                    qb.download_from_link(magnet, savepath=d_path)
                    time.sleep(90)
                    torrents = qb.torrents(filter='downloading')
                    # for k in info_hash
                    # k.Info code
                    # print("This is the info")

                    path_torrent = Torrent_details(torrents, qb, s['title'])
                    print(
                        '--------------------------------------------------------------------------------------'
                    )
        else:
            print("Not found")
    return HttpResponse(path_torrent)
Exemplo n.º 10
0
def main():

    qb = Client('http://127.0.0.1:8080')
    qb.login()

    pool = eventlet.GreenPool(1)
    # Get Data
    rid = 0
    while True:
        log.warning(time.asctime(time.localtime()))

        try:
            data = qb.sync(rid)
            rid = data['rid']
            #pp.pprint(data.get('torrents'))
            check_if_torrent_finish(data.get('torrents'), pool, qb)
        except KeyboardInterrupt:
            break
        except:
            qb.login()
            rid = 0
            continue

        time.sleep(5 * 60)

    pass
Exemplo n.º 11
0
def add_client(clientIP, username, password):
    try:
        qb = Client(clientIP + "/")
        qb.login(username, password)
        return qb
    except:
        pass
Exemplo n.º 12
0
    def user_login(self):
        try:
            ip = self.var_ip.get()
            port = self.var_port.get()
            name = self.var_name.get()
            pwd = self.var_pwd.get()
            qb = Client('http://{ip}:{port}/'.format(ip=ip, port=port))
            qb.login(name, pwd)

            # 测试是否通过
            qb.torrents()

            self.controller.qb = qb
            self.controller.login_statu = True

            with open(USER_INFO_PATH,
                      "wb") as usr_file:  # with open with语句可以自动关闭资源
                usrs_info = {
                    "ip": ip,
                    'port': port,
                    'name': name,
                    'pwd': pwd
                }  # 以字典的形式保存账户和密码
                pickle.dump(usrs_info, usr_file)

        except Exception as exc:
            tk.messagebox.showerror('Error', '登录失败:%s' % exc)
Exemplo n.º 13
0
def download_torrent(order):
    qb = Client(URL)
    qb.login(user, password)
    app_data = ad.get_library_path()
    qb.download_from_link(order['magnet'], savepath=app_data['path'])
    db.insert_order(order)
    return 'downloading torrent'
Exemplo n.º 14
0
def get_torrent_info():
    qb = Client(URL)
    qb.login(user, password)
    torrents = qb.torrents()
    active_torrents = db.get_active_torrents()
    torr = []
    for i in range(len(torrents)):
        for a in active_torrents:
            if a[1] == torrents[i]['name']:
                info = {
                    'name': torrents[i]["name"],
                    'hash': torrents[i]["hash"],
                    'seeds': torrents[i]["num_seeds"],
                    'progress': torrents[i]['progress'],
                    'size': get_size_format(torrents[i]["total_size"]),
                    'speed': get_size_format(torrents[i]["dlspeed"]) + '/s'
                }
                torr.append(info)
                if torrents[i]['progress'] == 1:
                    db.finished_downloading_title(torrents[i]['name'])
                    ad.fix_files(torrents[i]['name'])
    # if no active torrents / stop seeding
    if len(torr) == 0:
        pause_all()
        return 'no torrents'
    return torr
Exemplo n.º 15
0
class QBitTorrentWrapper(object):
    def __init__(self, ip, username, password):
        self.ip = ip
        self.username = username
        self.password = password

        self.qb = Client(ip)
        self.qb.login(self.username, self.password)

    def addTorrentsFromFolder(self, dl_location_path):
        self.dl_location_path = dl_location_path

        for filename in filter(os.path.isfile, os.listdir(os.curdir)):
            if filename.endswith(".torrent"):
                torrent_file = open('%s' % filename, 'rb')
                self.qb.download_from_file(torrent_file,
                                           savepath=dl_location_path)

    def startDownloading(self):
        self.qb.resume_all()

    def stopDownloading(self):
        self.qb.pause_all()

    def timeInterval(self):
        schedule.every().day.at("00:00").do(self.startDownloading)
        schedule.every().day.at("06:00").do(self.stopDownloading)

        while True:
            schedule.run_pending()
Exemplo n.º 16
0
 def establishRPC(self, client, magnet_link=None, type="magnet"):
     print "• Establishing connection to", client
     try:
         if client == "transmission":
             tc = transmissionrpc.Client(self.transmission_url.split(":")[0],
                                         port=self.transmission_url.split(":")[1],
                                         user=self.transmission_user,
                                         password=self.transmission_password)
             if type == "magnet":
                 print "• Adding magnet to", client
                 tc.add_torrent(magnet_link)
             else:
                 print "• Adding torrent to", client
                 tc.add_torrent('file://' + os.path.abspath('torrent.torrent'))
         elif client == "qbittorrent":
             qb = Client(self.qbittorrent_url)
             qb.login(self.qbittorrent_user, self.qbittorrent_password)
             if qb._is_authenticated is True:
                 if type == "magnet":
                     print "• Adding magnet to", client
                     qb.download_from_link(magnet_link)
                 else:
                     print "• Adding torrent to", client
                     qb.download_from_file(file('torrent.torrent'))
     except:
         traceback.print_exc()
         raise IOError
Exemplo n.º 17
0
async def get_qb_client():
    try:
        qb = Client(config.qb_web_url)
        qb.login()
    except Exception as e:
        bot = nonebot.get_bot()
        msg = (
            "❌ 无法连接到 qbittorrent ,请检查:\n"
            "1.是否启动程序\n"
            "2.是否勾选了“Web用户界面(远程控制)”\n"
            f"3.连接地址、端口是否正确\nE: {e}"
        )
        logger.error(msg)
        await bot.send_msg(
            message_type="private", user_id=str(list(config.superusers)[0]), message=msg
        )
        return None
    try:
        qb.get_default_save_path()
    except Exception as e:
        bot = nonebot.get_bot()
        msg = f"❌ 无法连登录到 qbittorrent ,请检查是否勾选 “对本地主机上的客户端跳过身份验证”。\nE: {e}"
        logger.error(msg)
        await bot.send_msg(
            message_type="private", user_id=str(list(config.superusers)[0]), message=msg
        )
        return None
    return qb
Exemplo n.º 18
0
def watch_movie(torrent_link):
	try:
		qb = Client('http://' + qbittorrent_conf['ip'] + ':' + qbittorrent_conf['port'] + '/')

		qb.login(qbittorrent_conf['username'], qbittorrent_conf['password'])
		qb.download_from_link(torrent_link)
	except:
		print(error_message("You must enable qBittorrent Web UI for this to work."))
Exemplo n.º 19
0
def tor_info_message(message):
    startqtrnt()
    qb = Client('http://localhost:8080/')
    qb.login('admin', '1karina1')
    torrents = qb.torrents()
    for torrent in torrents:
        bot.send_message(message.chat.id, torrent['name'])
    qb.logout()
Exemplo n.º 20
0
def connectToClient(qb_client, qb_login, qb_password):
    # connect to the qbittorent Web UI
    qb = Client(qb_client)

    # put the credentials (as you configured)
    qb.login(qb_login, qb_password)

    return qb
Exemplo n.º 21
0
def dw_torrent(torrents, magnet_urls, host, login, password):
    qb = Client(f'http://{host}/')
    qb.login(login, password)
    if qb._is_authenticated:
        qb.download_from_file(torrents)
        qb.download_from_link(magnet_urls)
    else:
        raise NotTorrentClient
Exemplo n.º 22
0
def set_torrent_client():
	

	ip = socket.gethostbyname(socket.gethostname())
	qb = Client('http://'+ip+':8080/')
	qb.login()

	return qb
Exemplo n.º 23
0
class Bittorrent:
    def __init__(self):
        self.bittorrent = Client('http://localhost:8080/')
        self.bittorrent.login('pavo', 'buffalo12')
    
    def download(self, movie):
        filename = str(movie.metadata.title) + ' (' + str(movie.metadata.year) + ')'
        self.bittorrent.download_from_link(movie.metadata.magnet_link, savepath=filename)
Exemplo n.º 24
0
    def __init__(self, client):
        self.client = client

        qb = Client(os.getenv('QBT_URL'))

        qb.login('admin', os.getenv('QBT_KEY'))

        self.qb = qb
Exemplo n.º 25
0
def download(logger):
    # logger 설정
    # filename = re.sub('.py', '.log', os.path.basename(__file__))
    # log_dir = os.path.dirname(os.path.realpath(__file__))
    # logger = custom_logger_v2.set_logger(log_dir, filename)

    con = sqlite3.connect('db/avlist.db')
    cur = con.cursor()
    table_name = 'av_list'

    # 변수선언
    with open('conf/data.yml', 'rt', encoding='UTF8') as f:
        conf = yaml.load(f, Loader=yaml.FullLoader)

    qburl = conf['qburl']
    qbid = conf['qbid']
    qbpwd = conf['qbpwd']

    # qBittorrent 연결
    qb = Client(qburl)
    qb.login(qbid, qbpwd)

    # 미 다운로드 목록을 조회
    urls = []
    try:
        sql = "select title, url from av_list where qbittorrent_add = 'n' and url <> ''"
        cur.execute(sql)
        rows = cur.fetchall()
        # print(len(rows))
        for row in rows:
            urls.append((row[0], row[1]))

    except:
        logger.info("쿼리 실패")

    total_count = len(urls)
    count = 0

    for u in urls:
        logger.info("TITLE : " + u[0] + "\t\t" + "URL : " + u[1])
        try:
            qb.download_from_link(u[1])
            logger.info(u[0] + "\t" + "다운로드 요청 전송 성공")
            sql = "update av_list set qbittorrent_add = 'y' where title = '" + u[
                0] + "'"
            con.execute(sql)
            count += 1
            # print(sql)
        except Exception as ex:
            logger.info(u[0] + "\t" + "다운로드 요청 전송 실패")
            logger.error(ex)

    logger.info("총 " + total_count.__str__() + "건 중 " + count.__str__() +
                "건을 신규로 다운로드 요청하였습니다.")

    con.commit()
    con.close()
    return
Exemplo n.º 26
0
def download():
    # logger 설정
    filename = re.sub('.py', '.log', os.path.basename(__file__))
    log_dir = os.path.dirname(os.path.realpath(__file__))
    logger = custom_logger_v2.set_logger(log_dir, filename)

    # sqlite3 db 연결
    # 로그 저장할 폴더 생성
    # current_dir = os.path.dirname(os.path.realpath(__file__))
    # db_dir = '{}/db'.format(current_dir)
    # if not os.path.exists(db_dir):
    #     os.makedirs(db_dir)

    con = sqlite3.connect('../db/avlist.db')
    cur = con.cursor()
    table_name = 'av_list'

    # 변수선언
    with open('../conf/data.yml', 'rt', encoding='UTF8') as f:
        conf = yaml.load(f, Loader=yaml.FullLoader)

    qburl = conf['qburl']
    qbid = conf['qbid']
    qbpwd = conf['qbpwd']

    # qBittorrent 연결
    qb = Client(qburl)
    qb.login(qbid, qbpwd)

    # 미 다운로드 목록을 조회
    urls = []
    try:
        sql = "select title, url from av_list where qbittorrent_add = 'n' and url <> ''"
        cur.execute(sql)
        rows = cur.fetchall()
        print(len(rows))
        for row in rows:
            urls.append((row[0], row[1]))

    except:
        logger.info("쿼리 실패")

    for u in urls:
        logger.info("TITLE : " + u[0] + "\t\t" + "URL : " + u[1])
        try:
            qb.download_from_link(u[1])
            logger.info(u[0] + "\t" + "다운로드 요청 전송 성공")
            sql = "update av_list set qbittorrent_add = 'y' where title = '" + u[
                0] + "'"
            con.execute(sql)
            # print(sql)
        except:
            logger.info(u[0] + "\t" + "다운로드 요청 전송 실패")

    con.commit()
    con.close()
    return
Exemplo n.º 27
0
def search_database(request):
    found = False
    for root, dirs, files in os.walk("/media/HDD1/PlexContent/Movies"):
        for file in files:
            if temp[0] in file:
                found = True
    if found:
        return render(
            request, "movies/dbsearch.html",
            {"temp": temp[0] + " Found on Plex Server, no need to download!!"})

    else:
        options = Options()
        options.add_argument("--headless")  # Runs Chrome in headless mode.
        options.add_argument('--no-sandbox')  # # Bypass OS security model
        options.add_argument('start-maximized')
        options.add_argument('disable-infobars')
        options.add_argument("--disable-extensions")
        driver = webdriver.Chrome(
            chrome_options=options,
            executable_path=
            r'/home/littlejiver/Downloads/chromedriver_linux64/chromedriver')
        # driver = webdriver.Chrome(executable_path=r'/home/littlejiver/Downloads/chromedriver_linux64/chromedriver')
        wait = WebDriverWait(driver, 10)
        driver.get("https://www.zooqle.com/")

        wait.until(
            ec.element_to_be_clickable(
                (By.XPATH, '//div[@id="anp2-wrapper"]//div[text()="NO THANKS"]'
                 ))).click()
        wait.until(ec.element_to_be_clickable(
            (By.XPATH, '//input[@name="q"]'))).send_keys(temp[0])

        searchBar = wait.until(
            ec.element_to_be_clickable(
                (By.XPATH, '//div[@class="tt-dataset tt-datas' +
                 'et-qs"]//p[@class="tt-wrap tt-suggestion ' +
                 'tt-selectable"]//span[text()="' + temp[0] + '"]')))
        searchBar.click()
        wait.until(
            ec.element_to_be_clickable((
                By.XPATH,
                '//*[@id="body_container"]/div/div[1]/div[2]/div/table/tbody/tr[2]/td[2]/a'
            ))).click()
        magnetLink = wait.until(
            ec.element_to_be_clickable(
                (By.XPATH, '//*[@id="dlPanel"]/div[2]/ul/li[2]/a')))
        torrentLink = magnetLink.get_attribute("href")
        qb = Client("http://www.on-demandlogistics.com:8080/")
        qb.login("admin", "adminadmin")
        qb.download_from_link(torrentLink)
        task = torrent_downloading_progress.delay(1)
        return render(
            request, "movies/dbsearch.html", {
                "temp": "Downloading " + temp[0].title() + " now!",
                'task_id': task.task_id
            })
Exemplo n.º 28
0
    def __init__(self):
        super().__init__()
        self.host = input("输入客户端地址(http://IP:端口):")
        self.user = input("输入客户端用户名:")
        self.password = input("输入客户端密码:")

        qb = QbittorrentClient(self.host)
        print("开始连接 Qbittorrent 客户端...")
        qb.login(self.user, self.password)
        self.qb = qb
Exemplo n.º 29
0
def start_download(magnet, name, path):
    open_qb()
    try:
        qb = Client('http://127.0.0.1:8080/')
        qb.login()
        qb.download_from_link(magnet, savepath=path)
        print(name + " started downloading. The files will be saved to " +
              path + "\n")
    except Exception as e:
        print(e)
Exemplo n.º 30
0
def download_torrent():
	"""
	- Establece la conexión con qBitTorrent
	- Descarga los ficheros
	"""
	qb = Client(config.TORRENT['server'])
	qb.login(config.TORRENT['user'], config.TORRENT['pass'])
	qb.download_from_link(torrent_link, savepath=save_path)
	qb.logout()
	logger.info('✅ - {} en cola'.format(torrent_link))
Exemplo n.º 31
0
def main_proc():
    print('\n#################### [ Begin - Running at ' + time.ctime() + ' ] ##########')

    # load config
    with codecs.open('config.json', 'r', encoding='utf8') as f:
        cfg = json.loads(f.read())
    torrentcfg = cfg['torrent']
    policycfg = cfg['downloadpolicy']
    dbcfg = cfg['db']
    crawlcfg = cfg['crawl']

    # init db 
    db = DownloadDb(dbcfg)

    # get qbittorrent connection
    q = Client(torrentcfg['addr'])
    errmsg = q.login(torrentcfg['user'], torrentcfg['pwd'])
    if errmsg:
        print('Torrent server ' + errmsg, file=sys.stderr)
    
    # crawl
    t = TorrentKim3Net(
        crawlinfo = crawlcfg['torrentkim3.net'],
        downloadpolicy = policycfg
    )
    l = []
    for i in range(1, 3+1):
        l += t.getlist_tvdrama(page=i)
        l += t.getlist_variety(page=i)
        l += t.getlist_docu(page=i)
    
    print('\n########## Crawl torrentkim3.net')
    for each in l:
        subj = each['subject']
        matched = t.filtersubject(subj)
        if not matched:
            try:
                print('not matched : {}'.format(subj))
            except UnicodeEncodeError:
                print('not matched : {}'.format(subj.encode('cp949', 'replace')))
            continue

        magnet = t.getmagnetfrom(each['href'])
        if not magnet:
            print('failed to get magnet : ' + subj)
            continue

        if db.isadded(magnet):
            print('already added : ' + subj)
        else:
            q.download_from_link(magnet)
            print('added : '+ subj)
            db.added(magnet)
    
    db.sync()

    time.sleep(1)

    # check qbittorrent status

    print('\n########## QBittorrent Status')
    for each in q.torrents():
        progress = each['progress']
        percent = str(100 * progress) + ' %'
        name = each['name']
        magnet = 'magnet:?xt=urn:btih:' + each['hash'].lower()
        tr_files = map(lambda x: x['name'], q.get_torrent_files(each['hash']))
        print('+ ', percent + ' | ' + name + ' | ' + magnet)
        for each_file in tr_files:
            try:
                print('+-- ' + each_file)
            except UnicodeEncodeError:
                print('+-- {}'.format(each_file.encode('cp949', 'replace')))
        if progress == 1 and not db.isdownloaded(magnet):
            db.downloaded(magnet)

    db.sync()

    print('\n#################### [ End - Running at ' + time.ctime() + ' ] ##########')

    time.sleep (300)
from qbittorrent import Client

qb = Client('http://127.0.0.1:8080/')

qb.login()

torrents = qb.torrents()

for torrent in torrents:
    print torrent['name']