CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-telegraph

Python Telegraph API wrapper for creating and managing Telegraph pages and accounts

Overview
Eval results
Files

file-upload.mddocs/

File Upload

File upload functionality for Telegraph content. This feature allows uploading images and media files to Telegraph servers for use in pages.

Warning: File upload is NOT part of the official Telegraph API and should be used at your own risk.

Capabilities

Upload File

Upload files to Telegraph servers for use in page content.

def upload_file(f) -> list:
    """
    Upload file to Telegraph servers (unofficial API).

    Parameters:
    - f (str|file|list): File path, file-like object, or list of files.
                        Can also be tuple (file, filename) for custom naming.

    Returns:
    list: List of dicts with 'src' key containing the uploaded file URL

    Raises:
    TelegraphException: Upload failed or file type not allowed
    RetryAfterError: Rate limiting occurred
    """

Supported File Types

Only the following file types are allowed:

  • .jpg, .jpeg - JPEG images
  • .png - PNG images
  • .gif - GIF images
  • .mp4 - MP4 videos

Usage Examples

Upload Single File

from telegraph import Telegraph

telegraph = Telegraph()

# Upload by file path
result = telegraph.upload_file('image.jpg')
image_url = result[0]['src']
print(f"Uploaded to: https://telegra.ph{image_url}")

# Use in page content
telegraph.create_page(
    title='Image Post',
    html_content=f'<img src="{image_url}" alt="Uploaded image">'
)

Upload File-like Object

# Upload file-like object
with open('photo.png', 'rb') as f:
    result = telegraph.upload_file(f)
    image_url = result[0]['src']

Upload Multiple Files

# Upload multiple files
files = ['image1.jpg', 'image2.png', 'video.mp4']
results = telegraph.upload_file(files)

for i, result in enumerate(results):
    print(f"File {i+1} uploaded to: https://telegra.ph{result['src']}")

Upload with Custom Filename

# Upload with custom filename
with open('photo.jpg', 'rb') as f:
    result = telegraph.upload_file((f, 'custom_name.jpg'))
    image_url = result[0]['src']

Response Format

Successful uploads return a list of dictionaries with the following structure:

[
    {
        'src': '/file/abc123def456.jpg'  # Relative URL to uploaded file
    }
]

The full URL is https://telegra.ph + src value.

Error Handling

File upload operations may raise these exceptions:

from telegraph import Telegraph
from telegraph.exceptions import TelegraphException, RetryAfterError

telegraph = Telegraph()

try:
    result = telegraph.upload_file('large_file.jpg')
except RetryAfterError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except TelegraphException as e:
    print(f"Upload failed: {e}")

Common error scenarios:

  • File type not allowed: Attempting to upload unsupported file formats
  • File too large: Files exceeding Telegraph's size limits
  • Rate limiting: Too many uploads in short time period
  • Network errors: Connection issues during upload

Integration with Pages

Use uploaded files in page content:

# Upload image
result = telegraph.upload_file('chart.png')
image_src = result[0]['src']

# Create page with uploaded image
response = telegraph.create_page(
    title='Data Analysis Report',
    html_content=f'''
    <p>Here are the results of our analysis:</p>
    <figure>
        <img src="{image_src}" alt="Analysis Chart">
        <figcaption>Monthly sales data</figcaption>
    </figure>
    <p>As shown in the chart above...</p>
    '''
)

print(f"Page created: {response['url']}")

Best Practices

  1. Check file types before upload to avoid errors
  2. Handle rate limiting with appropriate retry logic
  3. Store returned URLs for use in page content
  4. Use descriptive filenames when uploading with custom names
  5. Optimize file sizes to improve upload performance
  6. Consider fallback options since this is unofficial API

Deprecated Function

The standalone upload_file function is deprecated but still available:

def upload_file(f) -> list:
    """
    Deprecated standalone upload function.
    
    Parameters:
    - f (str|file|list): File path, file-like object, or list of files
    
    Returns:
    list: List of src URL strings (not dicts like Telegraph.upload_file)
    
    Deprecated: Use Telegraph.upload_file() instead
    """

Usage comparison:

# Deprecated - don't use
from telegraph import upload_file
result = upload_file('image.jpg')  # Returns ['src1', 'src2', ...]
print(result)  # ['/file/abc123.jpg']

# Recommended approach
from telegraph import Telegraph
telegraph = Telegraph()
result = telegraph.upload_file('image.jpg')  # Returns [{'src': 'url'}, ...]
print(result)  # [{'src': '/file/abc123.jpg'}]

The deprecated function:

  • Returns only src URL strings, not full response objects
  • Issues deprecation warnings when used
  • May be removed in future versions
  • Provides less error information than the Telegraph class method

Install with Tessl CLI

npx tessl i tessl/pypi-telegraph

docs

account-management.md

async-api.md

file-upload.md

html-utilities.md

index.md

low-level-api.md

page-operations.md

tile.json