Page 1 of 1

Python script to clear completed downloads

Posted: Sat Jun 15, 2019 8:48 am
by jeremysherriff
Not strictly linux, but python is more common here I guess.

https://github.com/jeremysherriff/OpenF ... omplete.py
Complete script in first comment below in case repo gets moved/closed.

Code: Select all

clear_qbt_complete.py [option]
  Clears "Completed" status torrents from qBitTorrent
  Connects to "localhost:8080" without credentials
  Logs output to /var/log/clear_qbt_complete.log
  By default logs nothing to stdout/stderr to allow use in cron

  Options:
    -v --verbose : to enable console logging in addition to logfile
    -t --test    : for test mode (no delete) - implies -v
Edit: This script trigger the "also delete files on the hard disk" option, in case that was not clear.
That's what makes this different from simply setting the action on reaching seeding limit to "remove".

Re: Python script to clear completed downloads

Posted: Sat Jun 15, 2019 8:50 am
by jeremysherriff
Full code as promised:

Code: Select all

#!/usr/bin/python
import sys
import json
import requests
import logging
import argparse

# Set up logging - kinda important when deleting stuff!
logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s")
rootLogger = logging.getLogger()
fileHandler = logging.FileHandler("/var/log/clear_qbt_complete.log")
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
rootLogger.setLevel(logging.INFO)
debugmode = 0
if len(sys.argv) > 1 and ( str(sys.argv[1]) == '-v' or str(sys.argv[1]) == '--verbose' ):
    consoleHandler = logging.StreamHandler(sys.stdout)
    consoleHandler.setFormatter(logFormatter)
    rootLogger.addHandler(consoleHandler)
    rootLogger.setLevel(logging.DEBUG)
    debugmode = 1

testmode = 0
if len(sys.argv) > 1 and ( str(sys.argv[1]) == '-t' or str(sys.argv[1]) == '--test' ):
    consoleHandler = logging.StreamHandler(sys.stdout)
    consoleHandler.setFormatter(logFormatter)
    rootLogger.addHandler(consoleHandler)
    rootLogger.setLevel(logging.DEBUG)
    debugmode = 1
    testmode = 1

if len(sys.argv) > 1 and ( str(sys.argv[1]) == '-?' or str(sys.argv[1]) == '--help' ):
    print('clear_qbt_complete.py [option]')
    print('  Clears "Completed" status torrents from qBitTorrent')
    print('  Connects to "localhost:8080" without credentials')
    print('  Logs output to /var/log/clear_qbt_complete.log')
    print('  By default logs nothing to stdout/stderr to allow use in cron')
    print('')
    print('  Options:')
    print('    -v --verbose : to enable console logging in addition to logfile')
    print('    -t --test    : for test mode (no delete) - implies -v')
    print('')
    exit(0)

if len(sys.argv) > 1 and ( debugmode == 0 ):
    print('clear_qbt_complete.py: Invalid option "'+str(sys.argv[1])+'"')
    exit(1)

if len(sys.argv) > 2:
    print('clear_qbt_complete.py: Invalid option "'+str(sys.argv[2])+'"')
    exit(1)

# qBitTorrent server details, in URL format:
baseurl = 'http://localhost:8080'

# OK lets do stuff
exitcode = 0
url = '/query/torrents?filter=completed'
try:
    response = requests.get(baseurl+url)
    response.raise_for_status()
    data = response.json()
    # Observed status for torrents in 'completed' filter:
    #  uploading - seeding
    #  stalledUP - seeding but stalled
    # >pausedUP  - seeding and manually paused
    #            - seeding and ratio reached but seeding time still to go

    if len(data) == 0:
        logging.debug('No completed torrents to clear')
        if debugmode == 1:
            print('')
        exit(0)
    for tor in data:
        if tor['state'] != 'pausedUP':
            logging.debug('Skipping '+tor['state']+' torrent: '+tor['name'])
            continue
        logging.info('Clearing '+tor['state']+' torrent: '+tor['name'])
        payload = {'hashes': tor['hash']}
        url = '/command/deletePerm'
        if testmode == 0:
            try:
                response = requests.post(baseurl+url,data=payload)
                response.raise_for_status()
                logging.debug('POST data: '+str(payload))
            except requests.exceptions.RequestException as err:
                logging.error(str(err))
                exitcode = 1
    logging.debug('Exiting normally with code '+str(exitcode))
    if debugmode == 1:
        print('')
    exit(exitcode)
except requests.exceptions.RequestException as err:
    logging.error(str(err))
    if debugmode == 1:
        print('')
    exit(1)
Edit: Code clean-up for console output

Re: Python script to clear completed downloads

Posted: Thu Aug 15, 2019 3:48 am
by Leverz
How are you calling the script? I have searched and asked in a lot of places but no one seems to know, all I find are a huge number of people asking how it is done.

I just want to run a damn python script. :-\

Re: Python script to clear completed downloads

Posted: Thu Aug 15, 2019 6:33 pm
by jeremysherriff
I just call it in a cron job, same as any other script:

Code: Select all

mediabox@mediabox:~$ sudo crontab -l
19 14 * * *     /etc/webmin/package-updates/update.pl
1 18 * * *      /opt/custom/clear_qbt_complete.py
31 6 * * *      /opt/custom/radarr_search.py
21 9 * * *      /opt/custom/radarr_unmonitor_downloaded.py
14 16 * * *     /opt/custom/qbt_ipfilterlist.sh
mediabox@mediabox:~$

Re: Python script to clear completed downloads

Posted: Thu Aug 15, 2019 9:01 pm
by Leverz
Ahh, my bad, I thought you had used the built in execute tool.

Perhaps I will give the scheduler a go. Thanks for your time.