telegraph Python API Wrapper

repository·master·Indexed 43 days ago

https://github.com/python273/telegraph

A Python API wrapper for the Telegraph publishing platform. It provides synchronous and asynchronous (asyncio) clients to programmatically create accounts, publish and edit pages with HTML content, and retrieve page view statistics. Includes utilities for converting HTML to Telegraph-compatible nodes and a method for uploading images and videos.

Tokens
4K
Snippets
21
Records
22
Agent score
55%

What's inside telegraph

  1. Install telegraph

    master

    Install the standard synchronous version of the Telegraph API wrapper using pip:

    python3 -m pip install telegraph

    If you require asyncio support, install the package with the aio extra:

    python3 -m pip install 'telegraph[aio]'
    python3 -m pip install telegraph
    # or for asyncio support
    python3 -m pip install 'telegraph[aio]'
  2. Use the asynchronous Telegraph API with asyncio

    master

    To use the asynchronous API, import Telegraph from telegraph.aio. All API methods, such as create_account and create_page, must be awaited. This is useful for integration into existing asyncio event loops.

    import asyncio
    from telegraph.aio import Telegraph
    
    async def main():
        telegraph = Telegraph()
        print(await telegraph.create_account(short_name='1337'))
    
        response = await telegraph.create_page(
            'Hey',
            html_content='<p>Hello, world!</p>',
        )
        print(response['url'])
    
    asyncio.run(main())
  3. Use the synchronous Telegraph API

    master

    To use the synchronous API, import Telegraph from telegraph. You can create an account using create_account(short_name='...') and create pages using create_page(title, html_content='...'). The create_page method returns a dictionary containing the page's url.

    from telegraph import Telegraph
    
    telegraph = Telegraph()
    telegraph.create_account(short_name='1337')
    
    response = telegraph.create_page(
        'Hey',
        html_content='<p>Hello, world!</p>'
    )
    print(response['url'])
  4. Handle Telegraph API errors and rate limits

    master

    The library raises specific exceptions based on the API response:

    • TelegraphException: Raised when the API returns an error message.
    • RetryAfterError: Raised when the API returns a FLOOD_WAIT_ error. This error indicates rate limiting. The exception object contains the number of seconds you must wait before retrying.
    from telegraph.exceptions import RetryAfterError, TelegraphException
    
    try:
        telegraph.create_page(title='Test', html_content='<p>Hi</p>')
    except RetryAfterError as e:
        print(f"Rate limited. Wait {e} seconds.")
    except TelegraphException as e:
        print(f"API Error: {e}")
  5. Import the Telegraph client and exceptions

    master

    The telegraph package provides the Telegraph client for interacting with the Telegraph API, along with TelegraphException for error handling. You can import these directly from the package root.

    from telegraph import Telegraph, TelegraphException
  6. Manage Telegraph accounts with Telegraph

    master

    The Telegraph class provides several methods to manage your account:

    • create_account(short_name, author_name=None, author_url=None, replace_token=True): Creates a new account. If replace_token is True, the client's access_token is automatically updated to the new token.
    • edit_account_info(short_name=None, author_name=None, author_url=None): Updates account details. Pass only the fields you wish to change.
    • revoke_access_token(): Revokes the current token and generates a new one. Useful if a token is compromised. Returns a dictionary containing the new access_token and auth_url.
    • get_account_info(fields=None): Retrieves account details. Supported fields include: short_name, author_name, author_url, auth_url, and page_count.
    # Create an account
    account = telegraph.create_account(short_name='MyBot', author_name='Bot User')
    
    # Update account info
    telegraph.edit_account_info(author_name='New Name')
    
    # Get account info
    info = telegraph.get_account_info(fields=['page_count', 'short_name'])
  7. Retrieve page lists and view counts

    master

    Use these methods to explore content:

    • get_page_list(offset=0, limit=50): Returns a list of pages belonging to the current account, sorted by most recent.
    • get_views(path, year=None, month=None, day=None, hour=None): Returns the number of views for a specific page path. Note that if you provide month, you must also provide year. If you provide day, you must also provide month and year.
    # Example: Get recent pages
    pages = await telegraph.get_page_list(limit=10)
    
    # Example: Get views for a specific month
    views = await telegraph.get_views('My-Page-1-1-2024', year=2024, month=1)
  8. Upload files using TelegraphApi.upload_file

    master

    To upload files to Telegraph, instantiate a TelegraphApi object and call its upload_file method. The method accepts a file-like object f and returns a list of strings containing the source URLs (src) of the uploaded files.

    Note: The top-level telegraph.upload_file function is deprecated. You should use the method on the TelegraphApi class instead.

    from telegraph.api import TelegraphApi
    
    api = TelegraphApi()
    urls = api.upload_file(your_file_object)
    # urls is a list of strings: ['https://telegra.ph/file1.png', ...]
  9. Convert HTML to Telegraph-compatible nodes with `html_to_nodes`

    master

    Use html_to_nodes(html_content) to transform an HTML string into a structured list of nodes (dictionaries and strings) that Telegraph understands.

    Constraints:

    • Only a specific subset of HTML tags is allowed (defined in ALLOWED_TAGS). If an unallowed tag is encountered, a NotAllowedTag exception is raised.
    • The input HTML must be well-formed. If tags are mismatched or unclosed, an InvalidHTML exception is raised.

    Allowed Tags include: a, aside, b, blockquote, br, code, em, figcaption, figure, h3, h4, hr, i, iframe, img, li, ol, p, pre, s, strong, u, ul, video.

    from telegraph.utils import html_to_nodes
    
    html = '<p>Hello <b>World</b></p>'
    nodes = html_to_nodes(html)
    # Resulting nodes will be a list of dictionaries and strings representing the structure.
  10. Serialize JSON with `json_dumps`

    master

    The json_dumps utility is a wrapper around json.dumps configured specifically for Telegraph's requirements. It uses separators=(',', ':') to produce compact JSON and sets ensure_ascii=False to support non-ASCII characters (like UTF-8) directly in the output.

    from telegraph.utils import json_dumps
    
    data = {"text": "Привет", "count": 1}
    json_string = json_dumps(data)
    # Result: '{"text":"Привет","count":1}'
  11. Use the Telegraph class for high-level API interactions

    master

    The Telegraph class is the primary helper for interacting with the Telegraph API. It manages authentication via an access_token and provides convenient methods for account and page management. It is recommended to use this class instead of TelegraphApi for most standard use cases.

    Initialization: Pass an access_token (optional) and a domain (defaults to 'telegra.ph').

    from telegraph import Telegraph
    
    telegraph = Telegraph(access_token='YOUR_ACCESS_TOKEN')
  12. Use the Telegraph class for asynchronous API interaction

    master

    The Telegraph class is the primary high-level helper for interacting with the Telegraph API asynchronously. It manages an internal TelegraphApi instance and provides convenient methods for account and page management. All methods in this class are async and must be awaited.

    To use it, initialize the class with an optional access_token and an optional domain (defaults to 'telegra.ph').

    from telegraph.aio import Telegraph
    
    async def main():
        telegraph = Telegraph(access_token='YOUR_TOKEN')
        # Use telegraph methods here