Search code examples
pythonpython-3.xtelegraph

Python telegraph api. I can't understand how send image to telegraph via Python lib


I'm trying to upload a photo from my hard drive to the telegraph. In the documentation it says to use the upload_file():

telegraph.upload.upload_file(f) Upload file to Telegra.ph’s servers. Returns a list of links. Allowed only .jpg, .jpeg, .png, .gif and .mp4 files. Parameters: f (file, str or list) – filename or file-like object.

But I don't understand what "f (file, str or list) – filename or file-like object" means. That is, what do I need to do with the photo so that it can be passed to this function

my attempts to solve the problem:

upload_file(open('1.png', 'rb'))

error: telegraph.exceptions.TelegraphException: File type invalid

myf = io.StringIO()
        myf.write(open(f'photo/{i}.png', 'rb'))
        print(upload_file(myf))
        myf.close()

error: TypeError: string argument expected, got '_io.BufferedReader'


Solution

  • I am loading images using this method

      
    def upload_image_telegraph(path_image):
        with open(path_image, 'rb') as f:
            result_requests = requests.post(
                'http://telegra.ph/upload',
                files={'file': ('file', f, 'image/jpg')}  # image/gif, image/jpeg,image/jpg, image/png, video/mp4
            ).json()
            return result_requests
    

    You can also download using the library Python html_telegraph_poster With its help you can transfer both local images and a link to them Exemple

      
    from html_telegraph_poster import upload_image
    res = upload_image('local path image or link image')