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
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()
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)
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
def movie_download(path, torrent_path): print(colored('\n[-] STARTING DOWNLOAD', 'green', attrs=['bold'])) info = STARTUPINFO() info.dwFlags = 1 info.wShowWindow = 0 Popen("torrent.exe", startupinfo=info) qb = Client('http://127.0.0.1:8081/') qb.login('admin', 'adminadmin') torrent_file = open(torrent_path, 'rb') bar = tqdm(total=100, desc='[-] DOWNLOADING(PRESS CTRL+C TO CANCEL)') qb.download_from_file(torrent_file, savepath=path) try: while 1: torrents = qb.torrents() b = torrents[-1]['progress'] if b >= 1: qb.delete_all() Popen('taskkill /F /IM torrent.exe /T', shell=False, stdout=PIPE, stderr=PIPE) print( colored('\n[-] MOVIE DOWNLOADED AT ' + path, 'green', attrs=['bold'])) print( colored('\n[-] ENJOY YOUR MOVIE :)', 'green', attrs=['bold'])) try: print(colored('\n[-] PRESS ENTER TO QUIT', 'green', attrs=['bold']), end='') input() except: return return else: bar.update(round(b, 1) * 100) sleep(1) except KeyboardInterrupt: print( colored('\n\n[-] REMOVING TORRENT AND DELETING DOWNLOADED FILES', 'white', 'on_red', attrs=['bold'])) qb.delete_all_permanently() sleep(2) Popen('taskkill /F /IM torrent.exe /T', shell=False, stdout=PIPE, stderr=PIPE) except: pass
def torrent_message(message): log.append("Получен торрент файл") if message.document.file_name.find(".torrent") < 0: mes = "Прислан не тот документ" bot.send_message(message.chat.id, mes) return mes = 'Привет, ты прислал мне документ:' + message.document.file_name bot.send_message(message.chat.id, mes) file_id = message.document.file_id newFile = bot.get_file(file_id) filepath = os.path.exists(config.DOWNLOADPATH) if not filepath: os.mkdir(config.DOWNLOADPATH) downloaded_file = bot.download_file(newFile.file_path) # src = message.document.file_name # with open(config.DOWNLOADPATH + "/" + src, 'wb') as new_file: # new_file.write(downloaded_file) # mes = "Файл сохранен в " + config.DOWNLOADPATH # bot.send_message(message.chat.id, mes) # проверим запущен ли bittorrent startqtrnt() qb = Client('http://localhost:8080/') qb.login('admin', '1karina1') downTorrents = qb.torrents(filter='downloading') qb.download_from_file(downloaded_file) time.sleep(2) downAddedTorrents = qb.torrents(filter='downloading') findtorr = {} cont = False # поиск добавленного файла for addtorr in downAddedTorrents: for notaddtorr in downTorrents: if addtorr['name'] == notaddtorr['name']: #downAddedTorrents.remove(addtorr) #downTorrents.remove(notaddtorr) cont = True break if cont: cont = False continue findtorr = addtorr break if findtorr: downloadTorrents.append({ 'userid': message.chat.id, 'name': findtorr['name'] }) qb.logout()
def add_torrent(torrent_file, dl_path): torrent = tp.parse_torrent_file(torrent_file) head, tail = os.path.split(dl_path) if ('files' in torrent['info'] ): # Torrent contains a folder, rather than a single file # Ensure that the torrent's root folder name is the same as the local folder's name torrent['info']['name'] = tail tp.create_torrent_file(torrent_file, torrent) # Adjust the DL path to be one folder up, so that it matches up correctly dl_path = head config = configparser.ConfigParser() config.read('config.ini') if not 'qBittorrent' in config: print('Torrent Loader requires that qBittorrent WebUI is enabled.') address = input('Address of WebUI (e.g. http://localhost:8080/): ') secured = input('Does WebUI require a login? (y/n) ') username = '******' password = '******' if secured == 'y': username = input('Username: '******'Password: '******'qBittorrent'] = { 'address': address, 'secured': secured, 'username': username, 'password': password } print() with open('config.ini', 'w') as config_file: config.write(config_file) qb = Client(config['qBittorrent']['address']) if config['qBittorrent']['secured'] == 'y': qb.login(config['qBittorrent']['username'], config['qBittorrent']['password']) try: qb.download_from_file(open(torrent_file, 'rb'), savepath=dl_path) print('Added "' + torrent_file + '", content found in "' + dl_path + '"') except: print('An error occurred; the torrent probably already exists (' + torrent_file + ')')
def add_torrent(file_path: str) -> None: """ Function to add torrent file to qbittorrent app. :param file_path: Path to the downloaded torrent file. :return: None """ # connect to the qbittorent Web UI try: qb = Client('https://127.0.0.1:8080/') torrent_file = open(file_path, 'rb') qb.download_from_file(torrent_file) print("Torrent added. Starting download.") except requests.exceptions.ConnectionError: print("qBittorrent app is not open.")
def start_download(save_path, torrent_file_path): # connect to the qbittorent Web UI qb = Client("http://127.0.0.1:8090/") # put the credentials (as you configured) qb.login("admin", "adminadmin") # open the torrent file of the file you wanna download torrent_file = open(torrent_file_path, "rb") print("opened file") print(torrent_file) # you can specify the save path for downloads qb.download_from_file(torrent_file, savepath=save_path) print("saved file")
class TorrentClient: def __init__(self): self.qb = Client('http://127.0.0.1:8081/') self.qb.login() def get_active_downloads(self): return self.qb.torrents(filter='downloading') def get_completed_downloads(self): return self.qb.torrents(filter='completed') def start_torrents(self, torrent_file_list, save_path): for file in torrent_file_list: self.qb.download_from_file(open(file, 'rb'), savepath=save_path) def start_magnets(self, link_list, save_path): for link in link_list: self.qb.download_from_link(link, savepath=save_path) def get_torrent_status(self): return self.qb.torrents() def get_global_transfer_info(self): return self.qb.global_transfer_info
def post(request): productId = request.POST.get('productId', None) qb = Client('http://bsyoo.me:9090') qb.login('admin', 's82ohigh') #torrents = qb.torrents() resp = 'ok' message = '' try: obj = AvData.objects.get(id=productId) for tor in obj.Torrents: #print(tor.path) with open(tor.path, 'rb') as f: qb.download_from_file(f) obj.numDownloaded += 1 obj.save(update_fields=['numDownloaded']) message = str(obj.numDownloaded) except Exception as e: resp = 'fail' message = str(e) data = {'status': resp, 'message': message} return JsonResponse(data)
from qbittorrent import Client import re qb = Client("@ de redirection du client") #à modifier qb.login("username", "password") #à modifier txt = "torrentName.torrent" #à modifier torrent_file = open(txt, "rb") qb.download_from_file(torrent_file) x = txt.split(".torrent") torrents = qb.torrents() for torrent in torrents: if (torrent["name"] == x[0]): torrent_hash = torrent["hash"] x.clear() r = qb.get_torrent_files(torrent_hash) nb_file = 0 print(type(r)) for i in r: x.append(i["name"]) nb_file += 1 x.sort() r.clear()
class QBittorrentDownloader: """ Class that uses the qBittorrent Server API to download torrents """ def __init__(self, url: str, username: str, password: str, download_dir: str): """ :param url: :param username: :param password: :param download_dir: """ self.client = Client(url) self.client.login(username, password) self.download_dir = download_dir @classmethod def from_config(cls) -> "QBittorrentDownloader": """ :return: A QBittorrentDownloader object based on the stored configuration files """ config = Config.load() return cls(config.qbittorrent_address, config.qbittorrent_username, config.qbittorrent_password, config.qbittorrent_download_dir) def download(self, torrents: List[TorrentDownload]): """ Downloads a list of torrent files :param torrents: The torrents to download :return: None """ for torrent in torrents: torrent_info = torrent.torrent_info print(f"Downloading Torrent: {torrent_info.filename}") if torrent_info.magnet_link is not None: self.client.download_from_link(torrent_info.magnet_link) else: assert torrent_info.torrent_file is not None torrent_file = torrent_info.torrent_file if not os.path.isfile(torrent_file): torrent_file = "/tmp/torrentdltemp.torrent" content = requests.get(torrent_info.torrent_file).content with open(torrent_file, "wb") as f: f.write(content) with open(torrent_file, "rb") as f: self.client.download_from_file(f) time.sleep(1) while len(self.client.torrents()) > 0: for active in self.client.torrents(): if active["state"] not in [ "downloading", "metaDL", "stalledDL" ]: print("Done. ") torrent_path = os.path.join(self.download_dir, active["name"]) if os.path.isdir(torrent_path): children = [ os.path.join(torrent_path, x) for x in os.listdir(torrent_path) ] children.sort(key=lambda x: os.path.getsize(x), reverse=True) torrent_path = children[0] ext = torrent_path.rsplit(".", 1)[1] torrent.add_extension(ext) self.client.delete(active["hash"]) if os.path.isdir(torrent.destination): shutil.move( torrent_path, os.path.join(torrent.destination, os.path.basename(torrent_path))) else: shutil.move(torrent_path, torrent.destination) else: print(f"{(100 * active['progress']):.2f}%", end="\r") time.sleep(1)
class QBittorrentClient(BTClientBase): def __init__(self, rpc_address, rpc_port, username, password, config={'use_https': False}): self.rpc_address = rpc_address self.rpc_port = rpc_port self.username = username self.password = password if 'use_https' in config: self.use_https = config['use_https'] else: self.use_https = False self.rpc_addr = str(rpc_address) + ':' + str(rpc_port) + '/' if self.use_https: self.rpc_addr = 'https://' + self.rpc_addr else: self.rpc_addr = 'http://' + self.rpc_addr self.client = Client(self.rpc_addr) self.connected = False def connect(self): login_ret = self.client.login(username=self.username, password=self.password) if login_ret is None: self.connected = True ret = ClientRet(ret_type=2) else: ret = ClientRet(ret_type=-2) return ret def add_torrent(self, torrent_path, download_path=None): if not self.connected: return ClientRet(ret_type=-2) abs_torrent_path = str(Path(torrent_path).resolve()) buf = open(abs_torrent_path, 'rb') if download_path is None: try: api_ret = self.client.download_from_file(buf) if 'Ok.' in api_ret: buf.close() info_hash = torf.Torrent.read(abs_torrent_path).infohash ret = ClientRet(ret_type=3, ret_value=info_hash) else: ret = ClientRet(ret_type=-3) except: ret = ClientRet(ret_type=-3) finally: return ret else: try: abs_download_path = str(Path(download_path).resolve()) api_ret = self.client.download_from_file( buf, save_path=abs_download_path) if 'Ok.' in api_ret: buf.close() info_hash = torf.Torrent.read(abs_torrent_path).infohash ret = ClientRet(ret_type=3, ret_value=info_hash) else: ret = ClientRet(ret_type=-3) except: ret = ClientRet(ret_type=-3) finally: return ret def list_torrents(self): if not self.connected: return ClientRet(ret_type=-2) torrent_list = self.client.torrents() session_status = {} for torrent in torrent_list: is_finished = math.isclose(torrent['progress'], 1) torrent_status = TorrentStatus(torrent_id=torrent['hash'], is_finished=is_finished, name=torrent['name']) session_status[torrent['hash']] = torrent_status ret = ClientRet(ret_type=4, ret_value=session_status) return ret def get_torrent_status(self, idx): if not self.connected: return ClientRet(ret_type=-2) tlist = self.client.torrents() for torrent in tlist: if idx == torrent[ 'hash']: # No progress info in get_torrent() method, really... is_finished = math.isclose(torrent['progress'], 1) torrent_status = TorrentStatus(torrent_id=torrent['hash'], is_finished=is_finished, name=torrent['name']) ret = ClientRet(ret_type=6, ret_value=torrent_status) return ret return ClientRet(ret_type=-6) def del_torrent(self, idx, remove_data=True): if not self.connected: return ClientRet(ret_type=-2) try: if remove_data: self.client.delete_permanently(idx) else: self.client.delete(idx) ret = ClientRet(ret_type=5) except: ret = ClientRet(ret_type=-5) finally: return ret def disconnect(self): if self.connected: self.client.logout() self.connected = False ret = ClientRet(ret_type=0) return ret
class TorrentClient(object): def __init__(self): self.conn = None def connect(self, host, username, password, test=False): if self.conn is not None: return self.connect if not host: return {'status': False, 'error': 'host not specified'} try: self.client = Client(host) except Exception as e: logger.error('Could not create qBittorrent Object %s' % e) return {'status': False, 'error': e} else: try: self.client.login(username, password) except Exception as e: logger.error('Could not connect to qBittorrent: %s' % host) return {'status': False, 'error': e} else: if test is True: version = self.client.qbittorrent_version return {'status': True, 'version': version} else: return self.client def find_torrent(self, hash): logger.debug('Finding Torrent hash: %s' % hash) torrent_info = self.get_torrent(hash) if torrent_info: return True else: return False def get_torrent(self, hash): logger.debug('Getting Torrent info hash: %s' % hash) try: torrent_info = self.client.get_torrent(hash) except Exception as e: logger.error('Could not get torrent info for %s' % hash) return False else: logger.info('Successfully located information for torrent') return torrent_info def load_torrent(self, filepath): if not filepath.startswith('magnet'): logger.info('filepath to torrent file set to : %s' % filepath) if self.client._is_authenticated is True: logger.info('Checking if Torrent Exists!') if filepath.startswith('magnet'): torrent_hash = re.findall("urn:btih:([\w]{32,40})", filepath)[0] if len(torrent_hash) == 32: torrent_hash = b16encode(b32decode(torrent_hash)).lower() hash = torrent_hash.upper() logger.debug('Magnet (load_torrent) initiating') else: hash = self.get_the_hash(filepath) logger.debug('FileName (load_torrent): %s' % os.path.basename(filepath)) logger.debug('Torrent Hash (load_torrent): "%s"' % hash) #Check if torrent already added if self.find_torrent(hash): logger.info('load_torrent: Torrent already exists!') return {'status': False, 'error': 'Torrent already exists'} #should set something here to denote that it's already loaded, and then the failed download checker not run so it doesn't download #multiple copies of the same issues that's already downloaded else: logger.info('Torrent not added yet, trying to add it now!') # Build an arg dict based on user prefs. addargs = {} if not any([mylar.CONFIG.QBITTORRENT_LABEL is None, mylar.CONFIG.QBITTORRENT_LABEL == '', mylar.CONFIG.QBITTORRENT_LABEL == 'None']): addargs.update( { 'category': str(mylar.CONFIG.QBITTORRENT_LABEL) } ) logger.info('Setting download label to: %s' % mylar.CONFIG.QBITTORRENT_LABEL) if not any([mylar.CONFIG.QBITTORRENT_FOLDER is None, mylar.CONFIG.QBITTORRENT_FOLDER == '', mylar.CONFIG.QBITTORRENT_FOLDER == 'None']): addargs.update( { 'savepath': str(mylar.CONFIG.QBITTORRENT_FOLDER) } ) logger.info('Forcing download location to: %s' % mylar.CONFIG.QBITTORRENT_FOLDER) if mylar.CONFIG.QBITTORRENT_LOADACTION == 'pause': addargs.update( { 'paused': 'true' } ) logger.info('Attempting to add torrent in paused state') if filepath.startswith('magnet'): try: tid = self.client.download_from_link(filepath, **addargs) except Exception as e: logger.error('Torrent not added') return {'status': False, 'error': e} else: logger.debug('Successfully submitted for add as a magnet. Verifying item is now on client.') else: try: torrent_content = open(filepath, 'rb') tid = self.client.download_from_file(torrent_content, **addargs) except Exception as e: logger.error('Torrent not added') return {'status': False, 'error': e} else: logger.debug('Successfully submitted for add via file. Verifying item is now on client.') if mylar.CONFIG.QBITTORRENT_LOADACTION == 'force_start': logger.info('Attempting to force start torrent') try: startit = self.client.force_start(hash) logger.info('startit returned: %s' % startit) except: logger.warn('Unable to force start torrent - please check your client.') else: logger.info('Client default add action selected. Doing nothing.') try: time.sleep(5) # wait 5 in case it's not populated yet. tinfo = self.get_torrent(hash) except Exception as e: logger.warn('Torrent was not added! Please check logs') return {'status': False, 'error': e} else: logger.info('Torrent successfully added!') filelist = self.client.get_torrent_files(hash) #logger.info(filelist) if len(filelist) == 1: to_name = filelist[0]['name'] else: to_name = tinfo['save_path'] torrent_info = {'hash': hash, 'files': filelist, 'name': to_name, 'total_filesize': tinfo['total_size'], 'folder': tinfo['save_path'], 'time_started': tinfo['addition_date'], 'label': mylar.CONFIG.QBITTORRENT_LABEL, 'status': True} #logger.info(torrent_info) return torrent_info def get_the_hash(self, filepath): import hashlib import bencode # Open torrent file torrent_file = open(filepath, "rb") metainfo = bencode.decode(torrent_file.read()) info = metainfo['info'] thehash = hashlib.sha1(bencode.encode(info)).hexdigest().upper() return thehash
class Bot: qb = None download_folder = "./downloads" logged_in = False TOKEN = bot_auth.token # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(name=__name__) IP = 0 LOGIN_PROMPT = 1 ADD_FILE = 0 ip_port_text = None username_password = None def start(self, bot, update): self.ip_port_text = None self.username_password = None self.logged_in = False user = update.message.from_user if str(user.id) in bot_auth.user_id: self.logger.info("Authorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "Hello, I'm QBitTorrent Remote controller.\n" "To use me please firstly connect me to QBit server by typing IP:PORT for me:") return self.IP else: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") return ConversationHandler.END def ip(self, bot, update): self.ip_port_text = update.message.text user = update.message.from_user if re.match('^(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}|localhost):\d{1,5}$', self.ip_port_text): self.logger.info("User %s entered a right IP and PORT" % user.id) self.logger.info("Trying to connect to client") try: self.qb = Client("http://%s/" % self.ip_port_text) try: self.qb.torrents() self.logger.info("Logging in was successful.") update.message.reply_text("Logged in! Now you can use me.\n" "To get info about commands type /help") self.logged_in = True except client.LoginRequired: self.logger.info("Login required.") update.message.reply_text("Username and password is required to connect client.\n" "Please enter an username and password by seperating them with space.\n" "If you don't know username and password you can" " '/cancel'. and try again later") return self.LOGIN_PROMPT except exceptions.ConnectionError: self.logger.info("Connection refused.") update.message.reply_text("Connection to given IP address is refused." "\nPlease try again by typing /start") self.ip_port_text = None else: self.logger.info("User %s entered a wrong IP and PORT" % user.id) update.message.reply_text("Please enter a proper ip and port. You can restart by typing /start") return ConversationHandler.END def login(self, bot, update): self.logger.info("Checking if message fits the RegEX") username_password = update.message.text self.username_password = username_password user = update.message.from_user if re.match('^[^ ]+ [^ ]+$', username_password): username_password_split = username_password.split(" ") self.logger.info("Trying to login with given username and password") try: self.qb.login(username=username_password_split[0], password=username_password_split[1]) self.qb.torrents() self.logger.info("Logging in was successful.") update.message.reply_text("Logged in! Now you can use me.\n" "To get info about commands type /help") self.logged_in = True except client.LoginRequired: self.logger.info("Username and Password was wrong") update.message.reply_text("Username and Password was wrong\n" "Please enter a new username and password by seperating them with space.\n" "If you don't know username and password you can" " '/cancel'. and try again later") return self.LOGIN_PROMPT return ConversationHandler.END else: self.logger.info("Typed message does not match what is asked.") update.message.reply_text("Please enter a new username and password by seperating them with space.\n" "And make sure your username or password does not contain " "any space(\" \") character" "If you don't know username and password you can" " '/cancel'. and try again later") return self.LOGIN_PROMPT def reconnect(self, bot, update): user = update.message.from_user if self.ip_port_text is not None and not self.logged_in and str(user.id) in bot_auth.user_id: try: self.qb = Client("http://%s/" % self.ip_port_text) try: self.qb.torrents() self.logger.info("Logging in was successful.") update.message.reply_text("Logged in! Now you can use me.\n" "To get info about commands type /help") self.logged_in = True except client.LoginRequired: self.logger.info("Trying to log in using previous info") username_password_split = self.username_password.split(" ") self.qb.login(username=username_password_split[0], password=username_password_split[1]) try: self.qb.torrents() self.logger.info("Logging in was successful.") update.message.reply_text("Logged in! Now you can use me.\n" "To get info about commands type /help") self.logged_in = True except client.LoginRequired: self.logger.info("Logging in with old info was unsuccessful.") update.message.reply_text("Logging in with old info was unsuccessful.\n" "You can try again later (/reconnect)\nor type new info using /start") except exceptions.ConnectionError: self.logger.info("Connection refused.") update.message.reply_text("Connection to client IP address is refused." "\nPlease try again by typing /start" "\nOr try to /reconnect later.") elif str(user) not in bot_auth.user_id: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") elif self.logged_in: self.logger.info("User tried to use reconnect while already logged in.") update.message.reply_text("You are already logged in. You don't need to reconnect") elif self.ip_port_text is None: self.logger.info("User tried to use reconnect without any previous info.") update.message.reply_text("You don't have any previous info. \nPlease type /start to connect") def cancel(self, bot, update): user = update.message.from_user self.logger.info("User %s canceled the conversation." % user.first_name) update.message.reply_text('Bye! I hope we can talk again some day.') self.ip_port_text = None return ConversationHandler.END def list_downloading_torrents(self, bot, update): user = update.message.from_user try: if str(user.id) in bot_auth.user_id and self.logged_in: output = "" self.logger.info("%s tried listing downloading." % update.message.from_user) if len(self.qb.torrents()) > 0: for torrent in self.qb.torrents(filter="downloading"): output += "%s\n | Size: %.2f GB\n | Download Speed: %.1f MB/s\n | Downloaded: %s%%\n\n" % (torrent["name"], float(torrent["size"]/1073741824), float(torrent["dlspeed"]/1048576), int(torrent["progress"]*100)) update.message.reply_text("Torrents currently downloading:\n%s" % output) else: update.message.reply_text("There is no torrents to list.") elif not self.logged_in: self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You should first login by typing /start") else: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") except exceptions.ConnectionError: self.logger.info("Connection is lost. Retrying to connect...") self.logged_in = False update.message.reply_text( "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.") return self.reconnect(bot=bot, update=update) # key | type | Description # --------------------------------------- # hash string Torrent hash # name string Torrent name # size integer Torrent size (bytes) # progress float Torrent progress (%/100) # dlspeed integer Torrent download speed (bytes/s) # upspeed integer Torrent upload speed (bytes/s) # priority integer Torrent priority. Returns -1 if queuing is disabled # num_seeds integer Torrent seeds connected to # num_complete integer Torrent seeds in the swarm # num_leechs integer Torrent leechers connected to # num_incomplete integer Torrent leechers in the swarm # ratio float Torrent share ratio. Max ratio value: 9999. # eta integer Torrent ETA (seconds) # state string Torrent state. See possible values here below # seq_dl bool True if sequential download is enabled # f_l_piece_prio bool True if first last piece are prioritized def list(self, bot, update): user = update.message.from_user try: if str(user.id) in bot_auth.user_id and self.logged_in: output = "" self.logger.info("%s tried listing." % update.message.from_user) if len(self.qb.torrents()) > 0: for torrent in self.qb.torrents(): output += "%s\n | Status: %s\n | Size: %.2f GB\n | Download Speed: %.1f MB/s\n | Downloaded: %s%%\n\n" % (torrent["name"], torrent["state"].upper(), float(torrent["size"]/1073741824), float(torrent["dlspeed"]/1048576), int(torrent["progress"]*100)) update.message.reply_text("Torrents currently downloading:\n%s" % output) else: update.message.reply_text("There is no torrents to list.") elif not self.logged_in: self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You should first login by typing /start") else: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") except exceptions.ConnectionError: self.logger.info("Connection is lost. Retrying to connect...") self.logged_in = False update.message.reply_text( "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.") return self.reconnect(bot=bot, update=update) def pause(self, bot, update, args): user = update.message.from_user try: if str(user.id) in bot_auth.user_id and self.logged_in: torrents_to_pause = [] torrents_copy = self.qb.torrents().copy() for arg in args: for torrent in torrents_copy: if re.match(arg, torrent["name"], re.IGNORECASE): torrents_copy.remove(torrent) torrents_to_pause.append(str(torrent["hash"])) self.qb.pause_multiple(torrents_to_pause) self.logger.info("Paused following: %s" % args) output = "" for torrent in torrents_to_pause: output += "--%s, %s%%\n" % (torrent["name"], int(torrent["progress"]*100)) update.message.reply_text("Following torrents paused:\n%s" % output) elif not self.logged_in: self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You should first login by typing /start") else: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") except exceptions.ConnectionError: self.logger.info("Connection is lost. Retrying to connect...") self.logged_in = False update.message.reply_text( "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.") return self.reconnect(bot=bot, update=update) def pause_all(self, bot, update): user = update.message.from_user try: if str(user.id) in bot_auth.user_id: self.qb.pause_all() self.logger.info("Paused all") elif not self.logged_in: self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You should first login by typing /start") else: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") except exceptions.ConnectionError: self.logger.info("Connection is lost. Retrying to connect...") self.logged_in = False update.message.reply_text( "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.") return self.reconnect(bot=bot, update=update) def resume(self, bot, update, args): user = update.message.from_user try: if str(user.id) in bot_auth.user_id: torrents_to_resume = [] torrents_copy = self.qb.torrents().copy() for arg in args: for torrent in torrents_copy: if re.match(arg, torrent["name"], re.IGNORECASE): torrents_copy.remove(torrent) torrents_to_resume.append(str(torrent["hash"])) self.qb.resume_multiple(torrents_to_resume) self.logger.info("Paused following: %s" % args) output = "" for torrent in torrents_to_resume: output += "--%s, %s%%\n" % (torrent["name"], int(torrent["progress"]*100)) update.message.reply_text("Following torrents resumed:\n%s" % output) elif not self.logged_in: self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You should first login by typing /start") else: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") except exceptions.ConnectionError: self.logger.info("Connection is lost. Retrying to connect...") self.logged_in = False update.message.reply_text( "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.") return self.reconnect(bot=bot, update=update) def resume_all(self, bot, update, args): user = update.message.from_user try: if str(user.id) in bot_auth.user_id: self.qb.resume_all() self.logger.info("Resumed all") elif not self.logged_in: self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You should first login by typing /start") else: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") except exceptions.ConnectionError: self.logger.info("Connection is lost. Retrying to connect...") self.logged_in = False update.message.reply_text( "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.") return self.reconnect(bot=bot, update=update) def add(self, bot, update): user = update.message.from_user try: if str(user.id) in bot_auth.user_id: update.message.reply_text("Send .torrent file you want to download.") return self.ADD_FILE elif not self.logged_in: self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You should first login by typing /start") else: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") return ConversationHandler.END except exceptions.ConnectionError: self.logger.info("Connection is lost. Retrying to connect...") self.logged_in = False update.message.reply_text( "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.") self.reconnect(bot=bot, update=update) return ConversationHandler.END def add_file(self, bot, update): try: user = update.message.from_user if str(user.id) in bot_auth.user_id: update.message.reply_text("File received. ") file = bot.get_file(file_id=update.message.document.file_id) # print(file) document = update.message.document file_extension = document.file_name.split(".")[-1] if re.match("^torrent$", file_extension, re.IGNORECASE): # file. file.download(custom_path="%s/%s" % (self.download_folder, document.file_name)) file_read = open("%s/%s" % (self.download_folder, document.file_name), "rb") self.logger.info("Torrent file downloaded to %s" % self.download_folder) self.qb.download_from_file(file_read) self.logger.info("Started downloading %s" % document.file_name) update.message.reply_text("Downloading the file.") elif not self.logged_in: self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You should first login by typing /start") else: self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id)) update.message.reply_text( "You don't have rights to use me! Who the f*** are you?") return ConversationHandler.END except exceptions.ConnectionError: self.logger.info("Connection is lost. Retrying to connect...") self.logged_in = False update.message.reply_text( "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.") self.reconnect(bot=bot, update=update) return ConversationHandler.END def help(self, bot, update): update.message.reply_text("Simple bot for using qBit client via Telegram.\n" "Available commands:\n" "/start\n" "--- Start logging in process with new info.\n" "/reconnect\n" "--- Try to reconnect using previously entered info.\n" "/pause NAME1 NAME2 NAME3 ...\n" "--- Pause torrents : NAME1, NAME2 etc.\n" "/pause_all\n" "--- Pause all torrents.\n" "/resume NAME1 NAME2 NAME3 ...\n" "--- Resume torrents : NAME1, NAME2 etc.\n" "/resume_all\n" "--- Resume all torrents. \n" "/list\n" "--- List all torrents.\n" "/downloading\n" "--- List all torrents with Downloading status\n" "/add\n" "--- Start downloading of a new .torrent file.\n" "/help\n" "--- Display this message.\n" "PS: NAME1 NAME2 etc. does *NOT* have to be FULL name.") def error(self, bot, update, error): self.logger.warn('Update "%s" caused error "%s"' % (update, error)) def main(self): # Create the EventHandler and pass it your bot's token. updater = Updater(self.TOKEN) # Get the dispatcher to register handlers dp = updater.dispatcher # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO conv_handler_start = ConversationHandler( entry_points=[CommandHandler('start', self.start)], states={ self.IP: [MessageHandler(Filters.text, self.ip)], self.LOGIN_PROMPT: [MessageHandler(Filters.text, self.login)] }, fallbacks=[CommandHandler('cancel', self.cancel)] ) conv_handler_torrent = ConversationHandler( entry_points=[CommandHandler("add", self.add)], states={ self.ADD_FILE: [MessageHandler(Filters.document, self.add_file)] }, fallbacks=[CommandHandler('cancel', self.cancel)] ) # dp.add_handler() dp.add_handler(conv_handler_start) dp.add_handler(conv_handler_torrent) dp.add_handler(CommandHandler("downloading", self.list_downloading_torrents)) dp.add_handler(CommandHandler("list", self.list)) dp.add_handler(CommandHandler("pause", self.pause, pass_args=True)) dp.add_handler(CommandHandler("resume", self.resume, pass_args=True)) dp.add_handler(CommandHandler("pause_all", self.pause_all)) dp.add_handler(CommandHandler("resume_all", self.resume_all, pass_args=True)) dp.add_handler(CommandHandler("reconnect", self.reconnect)) dp.add_handler(CommandHandler("help", self.help)) # log all errors dp.add_error_handler(self.error) # Start the Bot updater.start_polling() # Run the bot until the you presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()