import urllib.parse
import requests
import json

# api token
api_token = '<your-API-token>'

# your subdomain 
subdomain = '<your-subdomain>'

# filter id (will be in the url of the filter after /f/filters/)
filterID = 11

# Fetch and download process
print("Starting...")
url = 'https://{subdomain}.fogbugz.com/api/listCases'.format(subdomain=subdomain)
response = requests.post(url, data=json.dumps({"token": api_token,"sFilter":filterID,"max": 100000,"cols": ["events"]}),headers = {'content-type': 'application/json'}).json()['data']['cases']
for case in response:
    caseNum = str(case['ixBug'])
    # Prints the case number for audit.
    print('Case: '+caseNum+'.')
    attNum = 0
    for att in case['events']:
        if len(att['rgAttachments']) > 0:            
            for item in att['rgAttachments']:
                attNum =attNum+1
                url = 'https://'+subdomain+'.fogbugz.com/'+urllib.parse.unquote(item['sURL']).replace('amp;','').replace('sTicket=', 'token='+api_token)
                r = requests.get(url, allow_redirects=True)
                filename = caseNum+'-'+item['sFileName'].replace('.unsafe','')
                open(filename, 'wb').write(r.content)
    # prints the number of attachments in the case. Each case can have multiple events and each event multiple attachments.
    print(str(attNum)+' attachments in this case.')
print('Finished.')
