How can I save Instagram stories in my media folder using media url?

669 Views Asked by At
def save_media(story_id, media_url):
try:
    link = media_url[:media_url.find('?')]
    extension = link[::-1][:link[::-1].find('.')+1][::-1]
    if 'video' in media_url:
        extension = '.mp4'
        
    filepath = r'{0}\file path for media to save stories\{1}{2}'.format(os.getcwd(), story_id, extension)
    if not os.path.exists(filepath):
        response = requests.get(media_url)
        if response.status_code==200:
            with open(r'{}'.format(filepath), 'wb') as file:
                file.write(response.content)
            file.close()
    newpath = filepath.replace(f'{os.getcwd()}\\influnite', '')
    return newpath
except Exception as error:
    print('Error saving story media!')
    print(error)
    return ''

media url is fetched from api after running this code i am not getting media data(videos and stories) in media folder someone can please tell what mistake am i doing?

1

There are 1 best solutions below

0
On BEST ANSWER
def save_media(story_id, media_url):
try:
    link = media_url[:media_url.find('?')]
    extension = link[::-1][:link[::-1].find('.')+1][::-1]
    if 'video' in media_url:
        extension = '.mp4'
        
    filepath = r'{0}/influnite/media/stories/{1}{2}'.format(os.getcwd(), story_id, extension)
    if not os.path.exists(filepath):
        response = requests.get(media_url)
        if response.status_code==200:
            with open(filepath, 'wb') as file:
                file.write(response.content)
            file.close()
    newpath = filepath.replace(r'{0}/influnite'.format(os.getcwd()), '')
    return newpath
except Exception as error:
    print('Error saving story media!')
    print(error)
    return ''

here first checked fetched that story is in jpg format or in mp4 and after that it check for response from server and it save story and in file as wb i.e. write in bits and it save story in media folder