python273 / telegraph

Telegraph API wrapper | Telegra.ph
https://pypi.org/project/telegraph/
MIT License
289 stars 45 forks source link

How to upload files (images, etc.) #30

Open vovkapultik opened 4 years ago

vovkapultik commented 4 years ago

It's not an issue, I just want to share this code

from telegraph import Telegraph, upload

telegraph = Telegraph()
telegraph.create_account(short_name='LetsTry')

def post(title, content):
    response = telegraph.create_page(title,
                                     html_content = content)
    return 'https://telegra.ph/{}'.format(response['path'])

files = '/Users/vovkapultik/Downloads/52920087_159420908268041_6560105268061929472_n.jpg'

imgpath = upload.upload_file(files)

print(imgpath)

#['/file/02a1613fc106b225b2b74.jpg']

postlink = post('Title', '<img src="/file/02a1613fc106b225b2b74.jpg">')

print(postlink)
MuuJian commented 2 years ago

imgpath = upload.upload_file(files)[0]['src'] postlink = post('Title', imgpath)

can write like this, bc upload_file() return a list of dicts with src key. (sorry, my english is poor.

Suharaz commented 1 year ago

Is there a way to upload multiple photos at once? bro

Sonico98 commented 1 month ago

Is there a way to upload multiple photos at once? bro

# Importing required package
from telegraph.aio import Telegraph
from pathlib import Path
import asyncio

# Declaring asynchronous function for using await
async def main():
    # Creating new Telegraph object
    telegraph = Telegraph()
    # Creating new account
    await telegraph.create_account("Test", author_name="Test")

    # Upload images in directory.
    image_dir = Path("~/Pictures/")
    uploaded_files = ""
    for path_object in image_dir.rglob("*"):
        if path_object.is_file():
            try:
                file = await telegraph.upload_file(path_object)
                uploaded_files += f'<img src={file[0]["src"]}>'
            except:
                print(f"Image {path_object} is probably too big")

    # Creating new page
    if uploaded_files != "":
        new_page = await telegraph.create_page(
            "Bulk",
            html_content=uploaded_files
        )
        # Printing page url into console
        print(new_page["url"])

# Running asynchronous function
asyncio.run(main())