Search code examples
pythonaccess-deniedpushbullet

Accessing an uploaded file's url


My application for sends and receives data from/to my phone - basically a 2-way communication through the pushbullet API.

I am trying to take a file from my phone and when it's uploaded do something with it, (play it for example if it's an audiofile).

But when I upload the file on my phone and then I list the pushes on my computer and get that exact push, the file-URLL is restricted.

I got following XML error-response showing "Access Denied" as message: XML error-response: Access Denied

403: Forbidden

How would I approach this?

Here is the code for the application:


def play_sound(url):
    #open the url and then write the contents into a local file
    open("play.mp3", 'wb').write(urlopen(url))
 
    #playsound through the playsound library
    playsound("play.mp3", False)


pb = pushbullet.Pushbullet(API_KEY, ENCRYPTION_PASSWORD)

pushes = pb.get_pushes()
past_pushes = len(pushes)
while True:
    time.sleep(3)

    # checks for new pushes on the phone and then scans them for commands
    pushes = pb.get_pushes()
    number_pushes = len(pushes) - past_pushes

    if number_pushes != 0:
        past_pushes = (len(pushes) - number_pushes)

        try:
            for i in range(number_pushes):
                push = pushes[i]

                push_body = push.get("body")

                if push_body is not None:
                    play = False

                    if push_body == "play":
                        play = True
                elif play:
                    #only runs if the user has asked to play something 
                    #beforehand

                    play = False
                    url = push.get('file_url')

                    #play sound from url
                    #this is where I get my 403: forbidden error
                    if url is not None and ".mp3" in url:
                        play_sound(url)

        except Exception as e:
            print(e)

Solution

  • From the docs...

    To authenticate for the API, use your access token in a header like Access-Token: <your_access_token_here>.

    You're using urlopen(url) without any header information, so the request is denied.

    So, try something like the following

    from urllib.request import Request, urlopen
    
    req = Request('https://dl.pushbulletusercontent.com/...')
    req.add_header('Access-Token', '<your token here>')
    content = urlopen(req).read()
    
    with open('sound.mp3', 'wb') as f:
      f.write(content)
    

    Reference: How do I set headers using python's urllib?