Search code examples
pythonpython-requestsslack-api7zip

Downloading encrpyted/compressed 7z file from slack url


Having an issue trying to download a encrypted/compressed 7zip file. I see the binary data being returned but still getting an error that the file is not downloaded. The information is being grabbed from a slack api by the 'url_private' property. The authentication is good, I see the byte data in my logger but still having issues.

import requests
import py7zr

url= "https://someurl/test_file.7z"
headers = {"auth": "token"}
response = requests.request("GET", url=file_url, headers=headers)
file_name = file_url.split("/")[-1]
if response.status_code == 200:
        with py7zr.SevenZipFile(file_name, mode='r', password=pw) as file:
            file.extractall(f"templates/files/")
            # logger.debug(file_data)
            file.close()

Error:

Failed to run listener function (error: [Errno 2] No such file or directory: 'test_file.7z')
Traceback (most recent call last):
  File "/opt/venv/lib/python3.8/site-packages/slack_bolt/listener/thread_runner.py", line 103, in run_ack_function_asynchronously
    listener.run_ack_function(request=request, response=response)
  File "/opt/venv/lib/python3.8/site-packages/slack_bolt/listener/custom_listener.py", line 49, in run_ack_function
    return self.ack_function(
  File "/app/app/routes/events.py", line 62, in handle_file_shared
    file = get_file_shared(file_url)
  File "/app/app/lib/file_shared.py", line 28, in get_file_shared
    with py7zr.SevenZipFile(file_name, mode='r', password=pw) as file:
  File "/opt/venv/lib/python3.8/site-packages/py7zr/py7zr.py", line 324, in __init__
    self.fp = open(file, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'test_file.7z'

I can't seem to find a solution, any help is appreciated.


Solution

  • You had most of it right. One of your problems might be that you didn't import the packages like requests. I found it by a simple google search.

    import os
    import requests
    import py7zr
    
    URL = "https://dl-alt1.winworldpc.com/Microsoft%20Windows%201.01%20Demo%20Slideshow%20(5.25).7z"
    filename = os.path.basename(URL)
    
    response = requests.get(URL, stream=True)
    
    if response.status_code == 200:
        with open(filename, 'wb') as out:
            out.write(response.content)
        with py7zr.SevenZipFile(filename, 'r') as archive:
            archive.extractall(f"templates/files/")
    else:
        print('Request failed: %d' % response.status_code)