Developer
Log in

SDKs

Python

Every action is a typed async method, every event a typed class you can match on, every piece of live state a typed dataclass. Python 3.10+ and asyncio, and it passes mypy --strict.

Install

The package is velum-studio-client, imported as velum_studio. Its only dependency is websockets. Types are frozen dataclasses with an Enum per set of words.

PyPI: coming soon

Until it's on PyPI, install it from source.

Shell
pip install path/to/sdk/python

Quick start

Python
import asyncio
from velum_studio import EventType, TopicType, VelumStudioClient

async def main() -> None:
    # The Studio running on this computer, found through its discovery file.
    async with await VelumStudioClient.connect(client_name="My App") as studio:
        studio.on(EventType.SCENE_CHANGED, lambda e: print(f"On air: {e.name}"))
        studio.on(EventType.ACTIVITY_RAID, lambda e: print(f"Raid: {e.amount.value if e.amount else 0} viewers"))

        # Topics bring their state and their events; state is filled when this returns.
        await studio.subscribe(TopicType.SCENES, TopicType.ACTIVITY)

        result = await studio.scene_switch(scene="Just Chatting")
        print(f"Switched to {result.name}")

        scenes = studio.state.scenes
        for scene in sorted(scenes.items.values(), key=lambda s: s.index):
            print("*" if scene.id == scenes.program else " ", scene.name)

        await asyncio.Event().wait()

asyncio.run(main())

Actions

Each action is one async method, named after its id, taking the action's parameters as keyword arguments and returning its result as a dataclass:

Action id Method Result
scene.switch await studio.scene_switch(scene="Just Chatting") SceneSwitchResult
audio.mute await studio.audio_mute(input="Mic", mode=AudioMuteMode.UNMUTE) AudioMuteResult
record.toggle await studio.record_toggle() RecordToggleResult
  • A fixed set of words is an Enum, a str enum, so the plain word works too.
  • await studio.run(ActionType.AUDIO_MUTE, AudioMuteParams(input="Mic")) runs an action chosen at run time and returns its typed result. ACTIONS lists every action with its name, description, group and parameters, for building pickers.
  • await studio.run_by_id("some.action", {...}) runs an action newer than this SDK.

Every action's exact signature is in the reference.

Events

Each event has its own class, deriving from the dataclass of its data. Register a handler per event, a plain function or a coroutine function:

Python
studio.on(EventType.CHAT_MESSAGE, lambda e: print(f"{e.author.display if e.author else ''}: {e.text}"))

Or take every event, typed, and match on its class:

Python
async for event in studio.events():
    match event:
        case SceneChangedEvent(name=name):
            print(f"On air: {name}")
        case ActivityRaidEvent(amount=ChatAmount(value=viewers)):
            print(f"Raid: {viewers:.0f} viewers")
        case ChatRow(text=text):
            print(f"{event.type.value}: {text}")   # every chat message and activity
  • Every event has type, its EventType.
  • An event comes while you follow its topic (TopicType.SCENES, CHAT, ACTIVITY). subscribe_events(EventType.ACTIVITY_RAID) follows the topics that bring the events you name, and EVENTS says which topic each needs.
  • Chat rows. ChatMessageEvent and the activity events all derive from ChatRow.
  • Handlers run as Studio's messages arrive, in order. One that raises doesn't stop the client: on_handler_error hears about it.
  • New words. A word Studio adds later (a new stream state, say) reads as the enum's UNKNOWN member, keeping the word as its value; a new kind of chat part reads as ChatPartUnknown.

State

studio.state holds each subscribed topic's latest value; on_state hears each change:

Python
await studio.subscribe(TopicType.AUDIO, TopicType.STREAM)
studio.on_state(TopicType.STREAM, lambda s: print(f"Stream: {s.state.value} for {s.seconds} s"))
mic = next(a for a in studio.state.audio.items.values() if a.name == "Mic")

fetch_state() reads topics once without following them.

Errors

Every error Studio sends raises its own class, deriving from VelumError, with Studio's plain-English message and its code:

Python
try:
    await studio.scene_switch(scene="Intermission")
except VelumNotFoundError:
    print("No such scene")
except VelumRateLimitedError as e:
    await asyncio.sleep(e.retry_after or 3)
except VelumError as e:
    print(f"{e.code}: {e}")

VelumConnectionError means Studio couldn't be reached, or the connection closed before the answer came. Every code's class is in the error reference.

Connecting

  • This computer. connect() reads Studio's discovery file, skips Studios that aren't running, and connects with the token in the Authorization header over the velum.v1 subprotocol.
  • Several Studios. find_running() lists them; pick one with instance_name= (or port=).
  • Reconnecting is on by default. When Studio restarts or the connection drops, the client reads the discovery file again, reconnects and follows the same topics again (on_disconnected, on_reconnected). See Events and reconnecting.
  • Another computer. Pair once with the QR code's link and keep the result privately. The connection is TLS that trusts only the certificate with the QR code's fingerprint, checked before the token is sent:
Python
device = await VelumStudioClient.pair(PairingLink.parse(qr_text), "Studio Deck")
Path("device.json").write_text(device.to_json())
studio = await VelumStudioClient.connect(device=PairedDevice.from_json(Path("device.json").read_text()))

Versioning

CATALOG_VERSION is the catalog version this SDK was generated from; studio.hello.catalog_version is the running Studio's. The package version is the generator's major version, then the catalog version (1.17.0 for catalog version 17); CATALOG_FINGERPRINT tells two builds of one catalog version apart. An older SDK keeps working with a newer Studio; the newer events arrive through on_unknown.

A complete example

A console app that lists scenes, switches them from the keyboard, and prints chat and activity. This is the SDK's own example, copied here when the site is built:

Pythonsdk/python/examples/console.py
# SPDX-License-Identifier: MIT
"""A small console app: connect to the Velum Studio running on this
computer, list its scenes, print scene changes, chat and activity as they
happen, and switch scenes from the keyboard.

    python examples/console.py
    python examples/console.py "Velum Studio (2)"     (another instance)
"""

import asyncio
import sys

from velum_studio import ChatRow, EventType, SceneChangedEvent, StudioEvent, TopicType, VelumError, VelumStudioClient


async def main() -> int:
    studio = await VelumStudioClient.connect(client_name="Sample console", instance_name=sys.argv[1] if len(sys.argv) > 1 else None)
    async with studio:
        print(f"Connected to {studio.hello.instance_name} {studio.hello.version}.")

        def on_event(e: StudioEvent) -> None:
            match e:
                case SceneChangedEvent(name=name):
                    print(f"On air: {name}")
                case ChatRow() if e.type is EventType.CHAT_MESSAGE:
                    print(f"[{e.platform.value}] {e.author.display if e.author else ''}: {e.text}")
                case ChatRow():
                    print(f"{e.type.value}: {e.text}")

        studio.on_event(on_event)
        studio.on_disconnected(lambda d: print(f"Disconnected ({d.reason}){'; reconnecting…' if d.reconnecting else ''}"))
        studio.on_reconnected(lambda h: print(f"Reconnected to {h.instance_name}."))
        await studio.subscribe(TopicType.SCENES, TopicType.CHAT, TopicType.ACTIVITY)

        while True:
            state = studio.state.scenes
            assert state is not None  # subscribed above
            scenes = sorted(state.items.values(), key=lambda s: s.index)
            for i, s in enumerate(scenes, 1):
                print(f" {'*' if s.id == state.program else ' '} {i}. {s.name}")
            line = (await asyncio.to_thread(input, "Number to put on air, q to quit: ")).strip()
            if line == "q":
                return 0
            if line.isdigit() and 1 <= int(line) <= len(scenes):
                try:
                    r = await studio.scene_switch(scene=scenes[int(line) - 1].id)
                    print(f"Switched to {r.name}.")
                except VelumError as e:
                    print(f"Studio said: {e}")


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))
Shell
python examples/console.py
python examples/console.py "Velum Studio (2)"     # another instance

to open · ↑ ↓ to move · Esc to close