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)
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')
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']), ) )
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()
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))
def tor_info_message(message): startqtrnt() qb = Client('http://localhost:8080/') qb.login('admin', '1karina1') torrents = qb.torrents(filter='downloading') if not torrents: bot.send_message(message.chat.id, 'Нет не загруженных торрентов') return for torrent in torrents: bot.send_message(message.chat.id, torrent['name']) qb.logout()
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 torrent(self, msg, args): # a command callable with !tryme """ url or magnet add (one by one) """ send_id = msg.to if msg.to == self.bot_identifier: send_id = msg.frm if msg.frm != self.build_identifier(bot_define.BOT_ADMIN_ID): # deny! stream = self.send_stream_request( send_id, open(os.getcwd() + '/resources/deny_new.jpg', 'rb'), name='deny_new.jpg', stream_type='photo') return self.log.info('args: ' + args) validations = ['http://', 'magnet:', 'https://', 'bc://bt/'] if all(not (val in args) for val in validations): stream = self.send_stream_request( send_id, open(os.getcwd() + '/resources/nooo.gif', 'rb'), name='nooo.gif', stream_type='document') return qb = Client(bot_define.TORRENT_URL) yield "Request Login" res = qb.login(bot_define.TORRENT_USER_NAME, bot_define.TORRENT_PASSWORD) if res: yield "Failed to Login" return yield "Request Torrent Job!" res = qb.download_from_link(args) if res: yield "Something has wrong!" return stream = self.send_stream_request( send_id, open(os.getcwd() + '/resources/sloth.gif', 'rb'), name='sloth.gif', stream_type='document') yield "Request Done." qb.logout()
class QB: def __enter__(self): try: self.connection = Client(config.qbt_host) self.connection.login(config.qbt_user, config.qbt_pass) return self.connection except ConnectionError: log("Error connecting to qBittorrent Web UI", important=True, context="QB") raise ConnectionError def __exit__(self, exc_type, exc_val, exc_tb): try: self.connection.logout() except LoginRequired: log("QBT Error: Not logged in!", context="QB")
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
log.info('Starting paused torrents...') torrents = qb.torrents(filter='paused') no_of_torrents = len(torrents) i = 0 for torrent in torrents: if DO_NOT_RESUME_TAG not in torrent['tags']: if DRY_RUN != 'yes': qb.resume(torrent['hash']) log.debug('Torrent name: %s started%s', torrent['name'], ' [SIMULATED]' if DRY_RUN == 'yes' else '') i = i + 1 else: log.debug('Torrent name: %s not resumed as tag %s avoids it%s', torrent['name'], DO_NOT_RESUME_TAG, ' [SIMULATED]' if DRY_RUN == 'yes' else '') log.info('Started %d of %d torrents.', i, no_of_torrents) else: log.info('Pausing active torrents...') torrents = qb.torrents(filter='downloading') no_of_torrents = len(torrents) i = 0 for torrent in torrents: if torrent['state'] == 'downloading' or torrent['state'] == 'queuedDL' or torrent['state'] == 'stalledDL': if DO_NOT_PAUSE_TAG not in torrent['tags']: if DRY_RUN != 'yes': qb.pause(torrent['hash']) log.debug('Torrent name: %s paused%s', torrent['name'], ' [SIMULATED]' if DRY_RUN == 'yes' else '') i = i + 1 else: log.debug('Torrent name: %s not paused as tag %s avoids it%s', torrent['name'], DO_NOT_PAUSE_TAG, ' [SIMULATED]' if DRY_RUN == 'yes' else '') log.info('Paused %d of %d torrents.', i, no_of_torrents) qb.logout()