win11toast

repository·main·Indexed 43 days ago

https://github.com/github30/win11toast

A Python library for creating rich, interactive toast notifications on Windows 10 and 11 using the WinRT API. It supports custom XML layouts, progress bars, interactive buttons, text inputs, OCR, text-to-speech, and asynchronous notifications via toast_async().

Tokens
2.9K
Snippets
12
Records
12
Agent score
6%

What's inside win11toast

  1. Basic usage of toast()

    main

    Use the toast() function to display a simple notification. You can provide a title and an optional body text.

    from win11toast import toast
    
    toast('Hello Python🐍')
  2. Run a Python script on toast click

    main

    You can trigger a local Python script when a toast is clicked by passing the path to the script in on_click.

    Note: Since the execution directory defaults to C:\Windows\system32, ensure your script handles paths correctly (e.g., using os.chdir()). For background execution without a visible console, consider using pythonw.exe.

    from win11toast import toast
    
    toast('Hello Pythonista', 'Click to run python script', on_click=r'C:\Users\Admin\Downloads\handler.pyw')
  3. Display progress bars in toasts

    main

    Use notify() to create an initial progress toast and update_progress() to update the status and value of an existing progress bar.

    from time import sleep
    from win11toast import notify, update_progress
    
    # Initialize progress
    notify(progress={
        'title': 'YouTube',
        'status': 'Downloading...',
        'value': '0',
        'valueStringOverride': '0/15 videos'
    })
    
    # Update progress in a loop
    for i in range(1, 15+1):
        sleep(1)
        update_progress({'value': i/15, 'valueStringOverride': f'{i}/15 videos'})
    
    # Final status update
    update_progress({'status': 'Completed!'})
  4. Configure toast icons and images

    main

    You can customize the visual appearance using icon and image parameters.

    • Icon: Small icon displayed in the toast. Can be a URL or a dictionary specifying src and placement (e.g., 'appLogoOverride' for a square look).
    • Image: Larger image. Can be a URL or a dictionary specifying src and placement (e.g., 'hero' for a large hero image).
    from win11toast import toast
    
    # Simple icon
    toast('Hello', 'Hello from Python', icon='https://unsplash.it/64?image=669')
    
    # Square icon via dictionary
    icon = {
        'src': 'https://unsplash.it/64?image=669',
        'placement': 'appLogoOverride'
    }
    toast('Hello', 'Hello from Python', icon=icon)
    
    # Hero image
    image = {
        'src': 'https://4.bp.blogspot.com/-u-uyq3FEqeY/UkJLl773BHI/AAAAAAAAYPQ/7bY05EeF1oI/s800/cooking_toaster.png',
        'placement': 'hero'
    }
    toast('Hello', 'Hello from Python', image=image)
  5. Add buttons and interactive elements

    main

    Enhance toasts with interactive elements:

    • Buttons: Use button (single) or buttons (list) to add actions. Buttons can be simple strings or dictionaries defining activationType (e.g., 'protocol'), arguments, and content.
    • Input: Add a text input field using input (the ID of the input) and a button to submit it.
    • Selection: Add a selection list using selection (list of options) and a button to submit the choice.
    from win11toast import toast
    
    # Simple button
    toast('Hello', 'Hello from Python', button='Dismiss')
    
    # Complex button (Protocol)
    toast('Hello', 'Click a button', buttons=[{'activationType': 'protocol', 'arguments': 'https://google.com', 'content': 'Open Google'}])
    
    # Multiple buttons
    toast('Hello', 'Click a button', buttons=['Approve', 'Dismiss', 'Other'])
    
    # Text Input
    toast('Hello', 'Type anything', input='reply', button='Send')
    
    # Selection list
    toast('Hello', 'Which do you like?', selection=['Apple', 'Banana', 'Grape'], button='Submit')
  6. Configure audio for toasts

    main

    Customize the sound played with the toast using the audio parameter. You can provide:

    • A system sound URI (e.g., ms-winsoundevent:Notification.Looping.Alarm).
    • A URL to an audio file.
    • A local file path.
    • A dictionary to enable loop or set the toast to silent.
    from win11toast import toast
    
    # System sound
    toast('Hello', 'Hello from Python', audio='ms-winsoundevent:Notification.Looping.Alarm')
    
    # URL audio
    toast('Hello', 'Hello from Python', audio='https://nyanpass.com/nyanpass.mp3')
    
    # Local file audio
    toast('Hello', 'Hello from Python', audio=r'C:\Users\Admin\Downloads\nyanpass.mp3')
    
    # Looping audio
    toast('Hello', 'Hello from Python', audio={'loop': 'true'})
    
    # Silent toast
    toast('Hello Python🐍', audio={'silent': 'true'})
  7. Add a body and click actions to a toast

    main

    You can add a body to the notification and define an on_click action. The on_click parameter can be a URL string or a callback function.

    from win11toast import toast
    
    # Open a URL on click
    toast('Hello Python', 'Click to open url', on_click='https://www.python.org')
    
    # Execute a callback function
    toast('Hello Python', 'Click to open url', on_click=lambda args: print('clicked!', args))
  8. Use OCR and Speech features

    main

    Win11toast supports Optical Character Recognition (OCR) and Text-to-Speech (Speak).

    • OCR: Pass a URL or a dictionary with lang and the local path to an image to extract text.
    • Speak: Use the dialogue parameter to have the system read text aloud.
    from win11toast import toast
    
    # OCR from URL
    toast(ocr='https://i.imgur.com/oYojrJW.png')
    
    # OCR with language and local file
    toast(ocr={'lang': 'ja', 'ocr': r'C:\Users\Admin\Downloads\hello.png'})
    
    # Text-to-Speech
    toast('Hello Python🐍', dialogue='Hello world')
  9. Use non-blocking and async toasts

    main

    Depending on your application flow, you can use different notification methods:

    • notify(): A non-blocking version of toast() that doesn't wait for the toast to be processed.
    • toast_async(): An asynchronous version for use in asyncio environments (like Jupyter notebooks).
    from win11toast import notify, toast_async
    import asyncio
    
    # Non-blocking
    notify('Hello Python', 'Non-blocking message')
    
    # Async usage
    async def main():
        await toast_async('Hello Python', 'Async message')
    
    asyncio.run(main())
  10. Send custom XML notifications with toast()

    main

    For advanced notification layouts that go beyond the standard API parameters, you can pass a raw XML string to the toast() function using the xml keyword argument. This allows you to define complex toast structures including custom launch arguments, multiple text lines, specific image placements (like appLogoOverride or hero), and interactive actions like text inputs and background activation buttons.

    from win11toast import toast
    
    xml = """
    <toast launch="action=openThread&amp;threadId=92187">
        <visual>
            <binding template="ToastGeneric">
                <text hint-maxLines="1">Jill Bender</text>
                <text>Check out where we camped last weekend!</text>
                <image placement="appLogoOverride" hint-crop="circle" src="https://unsplash.it/64?image=1027"/>
                <image placement="hero" src="https://unsplash.it/360/180?image=1043"/>
            </binding>
        </visual>
        <actions>
            <input id="textBox" type="text" placeHolderContent="reply"/>
            <action
              content="Send"
              imageUri="Assets/Icons/send.png"
              hint-inputId="textBox"
              activationType="background"
              arguments="action=reply&amp;threadId=92187"/>
        </actions>
    </toast>"""
    
    toast(xml=xml)
  11. Configure toast duration and scenarios

    main

    Control how long a toast stays visible or its priority using duration and scenario.

    • duration: Set to 'long' to display for approximately 25 seconds.
    • scenario: Defines the toast's purpose (e.g., 'incomingCall', 'alarm', 'reminder', or 'urgent'). Certain scenarios may prevent the toast from timing out.
    from win11toast import toast
    
    # Long duration
    toast('Hello Python🐍', duration='long')
    
    # Specific scenario (e.g., no timeout for calls)
    toast('Hello Python🐍', scenario='incomingCall')