### Install simpleobsws Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Install the library using pip. Requires Python 3.9+. ```bash pip install simpleobsws ``` -------------------------------- ### WebSocketClient.connect Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Establishes the WebSocket connection to obs-websocket and starts the background receive task. The identification handshake begins automatically but completes asynchronously — call `wait_until_identified()` before sending requests. ```APIDOC ## WebSocketClient.connect ### Description Establishes the WebSocket connection to obs-websocket and starts the background receive task. The identification handshake begins automatically but completes asynchronously — call `wait_until_identified()` before sending requests. ### Returns - **bool**: True if the connection was newly established, False otherwise. ### Request Example ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): connected = await ws.connect() # Returns True if newly connected if not connected: print('Already connected or connection failed') return identified = await ws.wait_until_identified(timeout=10) if not identified: print('Identification timed out') await ws.disconnect() return print('Ready to send requests') await ws.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### WebSocketClient.__init__ Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Instantiate the client with the target WebSocket URL, an optional password, and optional identification parameters. No connection is made at construction time. ```APIDOC ## WebSocketClient.__init__ ### Description Instantiate the client with the target WebSocket URL, an optional password, and optional identification parameters. No connection is made at construction time. ### Parameters - **url** (string) - Optional - The WebSocket URL for obs-websocket. - **password** (string) - Optional - The password for authentication. - **identification_parameters** (IdentificationParameters) - Optional - Parameters to configure the identification handshake. ### Request Example ```python import simpleobsws # Minimal ws = simpleobsws.WebSocketClient() # Fully specified ws = simpleobsws.WebSocketClient( url='ws://192.168.1.50:4444', password='obs-password', identification_parameters=simpleobsws.IdentificationParameters( ignoreNonFatalRequestChecks=False, eventSubscriptions=0xFFFFFFFF # All event categories ) ) ``` ``` -------------------------------- ### Create WebSocketClient Instance Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Instantiate WebSocketClient with optional URL, password, and identification parameters. Connection is not made at construction. ```python import simpleobsws # Minimal — all arguments are optional ws = simpleobsws.WebSocketClient() # Fully specified ws = simpleobsws.WebSocketClient( url='ws://192.168.1.50:4444', password='obs-password', identification_parameters=simpleobsws.IdentificationParameters( ignoreNonFatalRequestChecks=False, eventSubscriptions=0xFFFFFFFF # All event categories ) ) ``` -------------------------------- ### WebSocketClient Initialization Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Initialize the WebSocketClient with optional URL, password, and identification parameters. ```APIDOC ## WebSocketClient ### `__init__(self, url: str = "ws://localhost:4444", password: str = '', identification_parameters: IdentificationParameters = IdentificationParameters()):` - `url` - WebSocket URL to reach obs-websocket at - `password` - The password set on the obs-websocket server (if any) - `identification_parameters` - An IdentificationParameters() object with session parameters to be set during identification ``` -------------------------------- ### Connect to WebSocket Server Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Establishes a connection to the configured OBS WebSocket server and initiates the identification handshake. ```APIDOC ### `async def connect(self):` - Returns `bool` | `True` if connected, `False` if not. Exceptions may still be raised by `websockets` Connect to the configured obs-websocket server. The library will automatically begin the identification handshake once connected. ``` -------------------------------- ### Connect and Identify WebSocket Client Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Establish WebSocket connection and wait for identification. Returns True if newly connected. Handles connection and identification timeouts. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): connected = await ws.connect() # Returns True if newly connected if not connected: print('Already connected or connection failed') return identified = await ws.wait_until_identified(timeout=10) if not identified: print('Identification timed out') await ws.disconnect() return print('Ready to send requests') await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### Register OBS Event Callbacks with simpleobsws Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Register asynchronous callbacks for OBS events. The callback signature determines argument delivery. Omitting the event argument captures all events. ```python import asyncio import simpleobsws # Subscribe to all event categories params = simpleobsws.IdentificationParameters(eventSubscriptions=0xFFFFFFFF) ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret', identification_parameters=params) # Catch-all: receives every event with full detail async def on_any_event(event_type, event_intent, event_data): print(f'[{event_type}] intent={event_intent} data={event_data}') # Targeted: only fires when the scene changes async def on_scene_change(event_data): print('Scene switched to:', event_data['sceneName']) # Targeted: only fires on stream state changes async def on_stream_state(event_data): print('Stream output state:', event_data['outputState']) async def main(): await ws.connect() await ws.wait_until_identified() ws.register_event_callback(on_any_event) ws.register_event_callback(on_scene_change, 'CurrentProgramSceneChanged') ws.register_event_callback(on_stream_state, 'StreamStateChanged') print('Listening for events. Press Ctrl+C to stop.') try: await asyncio.sleep(3600) # Listen for 1 hour except asyncio.CancelledError: pass ws.deregister_event_callback(on_scene_change, 'CurrentProgramSceneChanged') await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### Configure Session Identification Parameters Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Use IdentificationParameters to tune the identification handshake. Subscribe to specific event categories using bitwise OR. ```python import simpleobsws # Subscribe only to General (bit 0) and Scenes (bit 2) event categories params = simpleobsws.IdentificationParameters( ignoreNonFatalRequestChecks=False, # Strict request validation eventSubscriptions=(1 << 0) | (1 << 2) ) ws = simpleobsws.WebSocketClient( url='ws://localhost:4444', password='mypassword', identification_parameters=params ) ``` -------------------------------- ### Call a Batch of Requests Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Executes a batch of requests simultaneously and returns a list of `RequestResponse` objects. ```APIDOC ### `async def call_batch(self, requests: list, timeout: int = 15, halt_on_failure: bool = None, execution_type: RequestBatchExecutionType = None, variables: dict = None):` - Returns list of `RequestResponse` Call a request batch, which is to be completed all at once by obs-websocket. Feed it a list of requests, and it will return a list of results. - `requests` - List of requests to perform - `timeout` - How long to wait for the request batch to finish before giving up and throwing a `MessageTimeout` error - `halt_on_failure` - Tells obs-websocket to stop processing the request batch if one fails. Only available in serial modes - `execution_type` - `RequestBatchExecutionType` to use to process the batch - `variables` - Batch variables to use. Only available in serial modes ``` -------------------------------- ### Build OBS WebSocket Requests Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Create Request objects for obs-websocket commands. Supports requests with no data, with data payloads, and with batch variables for serial batches. ```python import simpleobsws # Simple request with no data req_version = simpleobsws.Request('GetVersion') # Request with data payload req_scene_item = simpleobsws.Request( 'GetSceneItemId', {'sceneName': 'MyScene', 'sourceName': 'MyCamera'} ) # Request with batch variables (serial batch only) req_with_vars = simpleobsws.Request( 'GetSceneItemTransform', requestData={'sceneName': 'MyScene', 'sceneItemId': 42}, outputVariables={'transform': 'sceneItemTransform'} ) ``` -------------------------------- ### Emit a Batch of Requests Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Executes a batch of requests without waiting for any responses. ```APIDOC ### `async def emit_batch(self, requests: list, halt_on_failure: bool = None, execution_type: RequestBatchExecutionType = None):` - Returns nothing Similar to the `call_batch()` function, but does not wait for an obs-websocket response. - `requests` - List of requests to perform - `halt_on_failure` - Tells obs-websocket to stop processing the request batch if one fails. Only available in serial modes - `execution_type` - `RequestBatchExecutionType` to use to process the batch - `variables` - Batch variables to use. Only available in serial modes ``` -------------------------------- ### Call a Single Request Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Sends a single request to the OBS WebSocket server and returns the `RequestResponse` object. ```APIDOC ### `async def call(self, request: Request, timeout: int = 15):` - Returns `RequestResponse` | Object with populated response data Make a request to the obs-websocket server and return the response. - `request` - The request object to perform the request with - `timeout` - How long to wait for obs-websocket responses before giving up and throwing a `MessageTimeout` error ``` -------------------------------- ### Check OBS Connection State with simpleobsws Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Returns `True` if the client is both connected and has completed the identification handshake. Use this to guard against sending requests on a stale or closed connection. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444') async def safe_call(request): if not ws.is_identified(): print('Not connected — reconnecting...') await ws.connect() await ws.wait_until_identified() return await ws.call(request) async def main(): result = await safe_call(simpleobsws.Request('GetVersion')) if result.ok(): print('OBS:', result.responseData['obsVersion']) await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### WebSocketClient.emit_batch Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Similar to `call_batch()`, but does not wait for a response from obs-websocket. This is useful for bulk updates where confirmation is not needed. ```APIDOC ## `WebSocketClient.emit_batch` — Fire-and-Forget Batch Like `call_batch()`, but does not wait for a response from obs-websocket. Useful for bulk updates where confirmation is not needed. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() await ws.wait_until_identified() # Mute multiple audio sources without waiting sources = ['Mic/Aux', 'Desktop Audio', 'Game Capture'] requests = [ simpleobsws.Request('SetInputMute', {'inputName': src, 'inputMuted': True}) for src in sources ] await ws.emit_batch( requests, halt_on_failure=False, execution_type=simpleobsws.RequestBatchExecutionType.Parallel ) await asyncio.sleep(0.5) await ws.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### Handle Exceptions in simpleobsws Source: https://context7.com/irltoolkit/simpleobsws/llms.txt This snippet demonstrates how to catch `NotIdentifiedError` for authentication or handshake failures and `MessageTimeout` for request timeouts. It also shows how to handle `EventRegistrationError` when attempting to register a non-async function as an event callback. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='wrongpassword') async def main(): await ws.connect() await ws.wait_until_identified(timeout=3) # NotIdentifiedError if authentication failed or handshake incomplete try: ret = await ws.call(simpleobsws.Request('GetVersion')) except simpleobsws.NotIdentifiedError as e: print('Not identified:', e) return except simpleobsws.MessageTimeout as e: print('Request timed out:', e) return # EventRegistrationError if a non-async function is registered def sync_callback(event_data): pass try: ws.register_event_callback(sync_callback, 'SomeEvent') except simpleobsws.EventRegistrationError as e: print('Must be async:', e) await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### Fire-and-Forget Batch with WebSocketClient.emit_batch Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Like `call_batch()`, but does not wait for a response from obs-websocket. Useful for bulk updates where confirmation is not needed. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() await ws.wait_until_identified() # Mute multiple audio sources without waiting sources = ['Mic/Aux', 'Desktop Audio', 'Game Capture'] requests = [ simpleobsws.Request('SetInputMute', {'inputName': src, 'inputMuted': True}) for src in sources ] await ws.emit_batch( requests, halt_on_failure=False, execution_type=simpleobsws.RequestBatchExecutionType.Parallel ) await asyncio.sleep(0.5) await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### WebSocketClient.call_batch Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Sends a list of `Request` objects as a single batch to obs-websocket and returns a list of `RequestResponse` objects in the same order. Supports parallel execution, per-frame serial execution, and real-time serial execution via `RequestBatchExecutionType`. ```APIDOC ## `WebSocketClient.call_batch` — Send Multiple Requests in One Round-Trip Sends a list of `Request` objects as a single batch to obs-websocket and returns a list of `RequestResponse` objects in the same order. Supports parallel execution, per-frame serial execution, and real-time serial execution via `RequestBatchExecutionType`. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() await ws.wait_until_identified() requests = [ simpleobsws.Request('GetVersion'), simpleobsws.Request('GetStats'), simpleobsws.Request('GetSceneList'), ] results = await ws.call_batch( requests, timeout=20, halt_on_failure=False, execution_type=simpleobsws.RequestBatchExecutionType.Parallel ) for req, res in zip(requests, results): if res.ok(): print(f'{req.requestType}: OK — {res.responseData}') else: print(f'{req.requestType}: FAILED — {res.requestStatus.comment}') await ws.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### Send Multiple Requests in One Round-Trip with WebSocketClient.call_batch Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Sends a list of `Request` objects as a single batch to obs-websocket and returns a list of `RequestResponse` objects in the same order. Supports parallel execution, per-frame serial execution, and real-time serial execution via `RequestBatchExecutionType`. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() await ws.wait_until_identified() requests = [ simpleobsws.Request('GetVersion'), simpleobsws.Request('GetStats'), simpleobsws.Request('GetSceneList'), ] results = await ws.call_batch( requests, timeout=20, halt_on_failure=False, execution_type=simpleobsws.RequestBatchExecutionType.Parallel ) for req, res in zip(requests, results): if res.ok(): print(f'{req.requestType}: OK — {res.responseData}') else: print(f'{req.requestType}: FAILED — {res.requestStatus.comment}') await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### Inspect Request Responses Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Examine RequestResponse objects returned by call() or call_batch(). Use .ok() to check success and .responseData to access results. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def inspect_response(): await ws.connect() await ws.wait_until_identified() ret = await ws.call(simpleobsws.Request('GetVersion')) print(ret.ok()) # True / False print(ret.has_data()) # True if responseData is present print(ret.requestType) # 'GetVersion' print(ret.requestStatus.result) # True print(ret.requestStatus.code) # 100 (RequestSuccess) print(ret.requestStatus.comment) # None (or error message string) print(ret.responseData) # {'obsVersion': '30.0.0', 'obsWebSocketVersion': '5.4.2', # 'rpcVersion': 1, 'availableRequests': [...], 'supportedImageFormats': [...]} await ws.disconnect() asyncio.run(inspect_response()) ``` -------------------------------- ### Send Request and Await Response with WebSocketClient.call Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Sends a single obs-websocket request and waits for the corresponding response. Raises `NotIdentifiedError` if not yet identified and `MessageTimeout` if no response arrives within the timeout window. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() await ws.wait_until_identified() # Get OBS version info ret = await ws.call(simpleobsws.Request('GetVersion')) if ret.ok(): print('OBS version:', ret.responseData['obsVersion']) # Get scene item ID with request data ret = await ws.call( simpleobsws.Request('GetSceneItemId', { 'sceneName': 'Main', 'sourceName': 'Webcam' }), timeout=10 ) if ret.ok(): print('Scene item ID:', ret.responseData['sceneItemId']) else: print('Failed:', ret.requestStatus.comment) # Get current video settings ret = await ws.call(simpleobsws.Request('GetVideoSettings')) if ret.ok(): print('Canvas: {}x{}'.format( ret.responseData['baseWidth'], ret.responseData['baseHeight'] )) await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### WebSocketClient.register_event_callback Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Registers an asynchronous callback function to listen for specific OBS WebSocket events. The callback can accept different numbers of arguments depending on the desired event data. ```APIDOC ## `WebSocketClient.register_event_callback` — Listen for OBS Events Registers an async callback for obs-websocket events. The callback signature determines how arguments are delivered: 1 parameter receives the raw payload dict; 2 parameters receive `(eventType, eventData)`; 3 parameters receive `(eventType, eventIntent, eventData)`. Omitting the `event` argument captures all events. ```python import asyncio import simpleobsws # Subscribe to all event categories params = simpleobsws.IdentificationParameters(eventSubscriptions=0xFFFFFFFF) ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret', identification_parameters=params) # Catch-all: receives every event with full detail async def on_any_event(event_type, event_intent, event_data): print(f'[{event_type}] intent={event_intent} data={event_data}') # Targeted: only fires when the scene changes async def on_scene_change(event_data): print('Scene switched to:', event_data['sceneName']) # Targeted: only fires on stream state changes async def on_stream_state(event_data): print('Stream output state:', event_data['outputState']) async def main(): await ws.connect() await ws.wait_until_identified() ws.register_event_callback(on_any_event) ws.register_event_callback(on_scene_change, 'CurrentProgramSceneChanged') ws.register_event_callback(on_stream_state, 'StreamStateChanged') print('Listening for events. Press Ctrl+C to stop.') try: await asyncio.sleep(3600) # Listen for 1 hour except asyncio.CancelledError: pass ws.deregister_event_callback(on_scene_change, 'CurrentProgramSceneChanged') await ws.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### register_event_callback Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Registers a coroutine callback function to be triggered by obs-websocket events. The behavior of argument passing to the callback depends on the number of parameters it accepts. ```APIDOC ## `def register_event_callback(self, callback, event: str = None):` ### Description Register a callback function for an obs-websocket event. Must be a coroutine. ### Parameters - `callback` (callable) - Callback to an async handler function. - `event` (str, optional) - Event name to trigger the callback. If not specified, all obs-websocket events will be sent to the callback. ### Callback Argument Handling - 1 parameter: Raw payload - 2 parameters: event type, event data - 3 parameters: event type, event intent, event data ``` -------------------------------- ### Control OBS Request Batch Execution with simpleobsws Source: https://context7.com/irltoolkit/simpleobsws/llms.txt An enum controlling how obs-websocket processes a batch of requests. Use `SerialFrame` for frame-accurate animation by processing one request per rendered video frame. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def animate_source(): await ws.connect() await ws.wait_until_identified() scene = 'Main' item_id = 12 # Obtained via GetSceneItemId beforehand # Build 60 per-frame position updates for smooth animation requests = [] for frame in range(60): x = frame * 16 # Move 16px per frame requests.append(simpleobsws.Request( 'SetSceneItemTransform', {'sceneName': scene, 'sceneItemId': item_id, 'sceneItemTransform': {'positionX': x, 'positionY': 100}} )) requests.append(simpleobsws.Request('Sleep', {'sleepFrames': 1})) # SerialFrame guarantees exactly one transform update per rendered frame responses = await ws.call_batch( requests, halt_on_failure=True, execution_type=simpleobsws.RequestBatchExecutionType.SerialFrame ) print(f'Processed {len(responses)} responses') await ws.disconnect() asyncio.run(animate_source()) ``` -------------------------------- ### Emit a Single Request Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Sends a single request to the OBS WebSocket server without waiting for a response. ```APIDOC ### `async def emit(self, request: Request)` - Returns nothing Similar to the `call()` function, but does not wait for an obs-websocket response. - `request` - The request object to emit to the server ``` -------------------------------- ### Fire-and-Forget Request with WebSocketClient.emit Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Sends a request to obs-websocket without waiting for a response. Useful for one-way commands where the result is not needed. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() await ws.wait_until_identified() # Trigger a scene switch without waiting for confirmation await ws.emit(simpleobsws.Request('SetCurrentProgramScene', { 'sceneName': 'BRB Screen' })) # Short pause so OBS can process before we disconnect await asyncio.sleep(0.5) await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### Await Handshake Completion with WebSocketClient.wait_until_identified Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Blocks until the obs-websocket identification handshake completes or the timeout is reached. Must be called before `call()` or `emit()`, otherwise `NotIdentifiedError` is raised. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() # Wait up to 5 seconds for identification if not await ws.wait_until_identified(timeout=5): print('Could not identify within 5 seconds') await ws.disconnect() return print('Identified:', ws.is_identified()) # True await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### Remove OBS Event Listener with simpleobsws Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Removes a previously registered callback. Both the function reference and the event name must match the original registration exactly. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444') async def on_scene_change(event_data): print('Scene changed:', event_data) async def main(): await ws.connect() await ws.wait_until_identified() ws.register_event_callback(on_scene_change, 'CurrentProgramSceneChanged') await asyncio.sleep(5) # Listen for 5 seconds # Remove the specific callback ws.deregister_event_callback(on_scene_change, 'CurrentProgramSceneChanged') print('Callback removed') await ws.disconnect() asyncio.run(main()) ``` -------------------------------- ### WebSocketClient.emit Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Sends a request to obs-websocket without waiting for a response. This is useful for one-way commands where the result is not needed. ```APIDOC ## `WebSocketClient.emit` — Fire-and-Forget Request Sends a request to obs-websocket without waiting for a response. Useful for one-way commands where the result is not needed. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() await ws.wait_until_identified() # Trigger a scene switch without waiting for confirmation await ws.emit(simpleobsws.Request('SetCurrentProgramScene', { 'sceneName': 'BRB Screen' })) # Short pause so OBS can process before we disconnect await asyncio.sleep(0.5) await ws.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### WebSocketClient.call Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Sends a single obs-websocket request and waits for the corresponding response. Raises `NotIdentifiedError` if not yet identified and `MessageTimeout` if no response arrives within the timeout window. ```APIDOC ## `WebSocketClient.call` — Send a Request and Await Response Sends a single obs-websocket request and waits for the corresponding response. Raises `NotIdentifiedError` if not yet identified and `MessageTimeout` if no response arrives within the timeout window. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() await ws.wait_until_identified() # Get OBS version info ret = await ws.call(simpleobsws.Request('GetVersion')) if ret.ok(): print('OBS version:', ret.responseData['obsVersion']) # Get scene item ID with request data ret = await ws.call( simpleobsws.Request('GetSceneItemId', { 'sceneName': 'Main', 'sourceName': 'Webcam' }), timeout=10 ) if ret.ok(): print('Scene item ID:', ret.responseData['sceneItemId']) else: print('Failed:', ret.requestStatus.comment) # Get current video settings ret = await ws.call(simpleobsws.Request('GetVideoSettings')) if ret.ok(): print('Canvas: {}x{}'.format( ret.responseData['baseWidth'], ret.responseData['baseHeight'] )) await ws.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### is_identified Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Checks if the client is currently connected to obs-websocket and has been successfully identified. ```APIDOC ## `def is_identified(self):` ### Description Checks if the client is connected and identified with the obs-websocket server. ### Returns - `bool` - `True` if connected and identified, `False` otherwise. ``` -------------------------------- ### WebSocketClient.call Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Sends a single request to obs-websocket and waits for a response. This method handles request correlation and returns a `RequestResponse` object. ```APIDOC ## WebSocketClient.call ### Description Sends a single request to obs-websocket and waits for a response. This method handles request correlation and returns a `RequestResponse` object. ### Parameters - **request** (Request) - Required - The request object to send. ### Returns - **RequestResponse**: An object containing the response from obs-websocket. ### Request Example ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def make_request(): await ws.connect() await ws.wait_until_identified() ret = await ws.call(simpleobsws.Request('GetVersion')) print(ret.ok()) # True / False print(ret.has_data()) # True if responseData is present print(ret.requestType) # 'GetVersion' print(ret.requestStatus.result) # True print(ret.requestStatus.code) # 100 (RequestSuccess) print(ret.requestStatus.comment) # None (or error message string) print(ret.responseData) # {'obsVersion': '30.0.0', 'obsWebSocketVersion': '5.4.2', # 'rpcVersion': 1, 'availableRequests': [...], 'supportedImageFormats': [...]} await ws.disconnect() asyncio.run(make_request()) ``` ``` -------------------------------- ### RequestBatchExecutionType Source: https://context7.com/irltoolkit/simpleobsws/llms.txt An enum that controls how a batch of requests is executed by the obs-websocket server, offering options for sequential or parallel processing. ```APIDOC ## `RequestBatchExecutionType` — Control Batch Execution Mode An enum controlling how obs-websocket processes a batch of requests. `SerialRealtime` processes sequentially in real time; `SerialFrame` processes one request per rendered video frame (enabling frame-accurate animation); `Parallel` processes all requests simultaneously. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def animate_source(): await ws.connect() await ws.wait_until_identified() scene = 'Main' item_id = 12 # Obtained via GetSceneItemId beforehand # Build 60 per-frame position updates for smooth animation requests = [] for frame in range(60): x = frame * 16 # Move 16px per frame requests.append(simpleobsws.Request( 'SetSceneItemTransform', {'sceneName': scene, 'sceneItemId': item_id, 'sceneItemTransform': {'positionX': x, 'positionY': 100}} )) requests.append(simpleobsws.Request('Sleep', {'sleepFrames': 1})) # SerialFrame guarantees exactly one transform update per rendered frame responses = await ws.call_batch( requests, halt_on_failure=True, execution_type=simpleobsws.RequestBatchExecutionType.SerialFrame ) print(f'Processed {len(responses)} responses') await ws.disconnect() asyncio.run(animate_source()) ``` ``` -------------------------------- ### WebSocketClient.wait_until_identified Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Blocks until the obs-websocket identification handshake completes or the timeout is reached. This method must be called before `call()` or `emit()` to avoid a `NotIdentifiedError`. ```APIDOC ## `WebSocketClient.wait_until_identified` — Await Handshake Completion Blocks until the obs-websocket identification handshake completes or the timeout is reached. Must be called before `call()` or `emit()`, otherwise `NotIdentifiedError` is raised. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444', password='secret') async def main(): await ws.connect() # Wait up to 5 seconds for identification if not await ws.wait_until_identified(timeout=5): print('Could not identify within 5 seconds') await ws.disconnect() return print('Identified:', ws.is_identified()) # True await ws.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### Wait for Identification Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Waits for the identification handshake to complete or until a specified timeout is reached. ```APIDOC ### `async def wait_until_identified(self, timeout: int = 10):` - Returns `bool` | `True` if identified, `False` if the timeout was reached Wait for the identification handshake to complete, or until the timeout is reached. - `timeout` - Time to wait until giving up (does not close the websocket connection) ``` -------------------------------- ### deregister_event_callback Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Deregisters a previously registered callback function from obs-websocket events. Requires matching function and event parameters to the original registration. ```APIDOC ## `def deregister_event_callback(self, callback, event = None):` ### Description Similar to `register()`, but deregisters a callback function from obs-websocket. Requires matching `function` and `event` parameters to the original callback registration. ### Parameters - `callback` (callable) - The callback function to deregister. - `event` (str, optional) - The specific event the callback was registered for. If not specified, attempts to deregister from all events. ``` -------------------------------- ### Disconnect from WebSocket Server Source: https://github.com/irltoolkit/simpleobsws/blob/master/usage.md Disconnects from the OBS WebSocket server. The server can be reconnected to using the `connect()` method. ```APIDOC ### `async def disconnect(self):` - Returns `bool` | `True` if disconnected, `False` if *already disconnected* Disconnect from the obs-websocket server. Once disconnected, the server may be connected to again using `connect()`. ``` -------------------------------- ### WebSocketClient.is_identified Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Checks if the WebSocket client is currently connected to the OBS server and has successfully completed the initial identification handshake. ```APIDOC ## `WebSocketClient.is_identified` — Check Connection State Returns `True` if the client is both connected and has completed the identification handshake. Use this to guard against sending requests on a stale or closed connection. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444') async def safe_call(request): if not ws.is_identified(): print('Not connected — reconnecting...') await ws.connect() await ws.wait_until_identified() return await ws.call(request) async def main(): result = await safe_call(simpleobsws.Request('GetVersion')) if result.ok(): print('OBS:', result.responseData['obsVersion']) await ws.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### WebSocketClient.deregister_event_callback Source: https://context7.com/irltoolkit/simpleobsws/llms.txt Removes a previously registered event listener. Both the function reference and the event name must match the original registration. ```APIDOC ## `WebSocketClient.deregister_event_callback` — Remove an Event Listener Removes a previously registered callback. Both the function reference and the event name must match the original registration exactly. ```python import asyncio import simpleobsws ws = simpleobsws.WebSocketClient(url='ws://localhost:4444') async def on_scene_change(event_data): print('Scene changed:', event_data) async def main(): await ws.connect() await ws.wait_until_identified() ws.register_event_callback(on_scene_change, 'CurrentProgramSceneChanged') await asyncio.sleep(5) # Listen for 5 seconds # Remove the specific callback ws.deregister_event_callback(on_scene_change, 'CurrentProgramSceneChanged') print('Callback removed') await ws.disconnect() asyncio.run(main()) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.