### Run Tests with Hatch Source: https://github.com/aatikturk/obsws-python/blob/main/README.md Install Hatch and run the project's tests. ```bash hatch test ``` -------------------------------- ### Install obsws-python using pip Source: https://github.com/aatikturk/obsws-python/blob/main/README.md Install the obsws-python library using pip. Ensure you have Python 3.9 or greater. ```bash pip install obsws-python ``` -------------------------------- ### Control Input Audio with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Manage audio inputs by listing, setting mute state, volume, balance, sync offset, and monitoring type. Also includes getting and setting input settings. Ensure the input names are correct for your OBS setup. ```python import obsws_python as obs with obs.ReqClient() as cl: # List all inputs (optionally filter by kind) inputs = cl.get_input_list() for inp in inputs.inputs: print(inp["inputName"], inp["inputKind"]) # Mute / unmute / toggle cl.set_input_mute("Mic/Aux", muted=True) cl.set_input_mute("Mic/Aux", muted=False) result = cl.toggle_input_mute("Mic/Aux") print(f"Now muted: {result.input_muted}") # Volume: set by multiplier (0–20) or dB (-100–26) cl.set_input_volume("Desktop Audio", vol_db=-6.0) vol = cl.get_input_volume("Desktop Audio") print(f"Volume: {vol.input_volume_db:.1f} dB") # Audio balance (0.0 = full left, 1.0 = full right) cl.set_input_audio_balance("Mic/Aux", 0.5) # Audio sync offset in milliseconds cl.set_input_audio_sync_offset("Mic/Aux", offset=100) # Monitor type cl.set_input_audio_monitor_type( "Desktop Audio", "OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT" ) # Get/set input settings settings = cl.get_input_settings("Browser Source") print(settings.input_settings) cl.set_input_settings("Browser Source", {"url": "https://example.com"}, overlay=True) ``` -------------------------------- ### Configuration File Example Source: https://github.com/aatikturk/obsws-python/blob/main/examples/levels/README.md This TOML file specifies connection details for OBS WebSocket. Ensure this file is placed in your user home directory. ```toml [connection] host = "localhost" port = 4455 password = "mystrongpass" ``` -------------------------------- ### Control Virtual Camera with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Start, stop, and toggle OBS's virtual camera output. This allows OBS to be used as a webcam source in other applications. ```python import obsws_python as obs with obs.ReqClient() as cl: status = cl.get_virtual_cam_status() print(f"Virtual cam active: {status.output_active}") cl.start_virtual_cam() result = cl.toggle_virtual_cam() print(f"Now active: {result.output_active}") cl.stop_virtual_cam() ``` -------------------------------- ### List and Control Outputs with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Manage OBS outputs beyond the main stream and record. This includes listing outputs, checking their status, starting, stopping, toggling, getting settings, and setting settings. Ensure the output name is correct. ```python import obsws_python as obs with obs.ReqClient() as cl: outputs = cl.get_output_list() for out in outputs.outputs: print(out["outputName"], out["outputActive"]) status = cl.get_output_status("virtualcam_output") print(f"Active: {status.output_active}") cl.start_output("virtualcam_output") cl.stop_output("virtualcam_output") result = cl.toggle_output("virtualcam_output") print(f"Now active: {result.output_active}") settings = cl.get_output_settings("virtualcam_output") print(settings.output_settings) cl.set_output_settings("virtualcam_output", {"delay": 0}) ``` -------------------------------- ### ReqClient — Virtual Camera Source: https://context7.com/aatikturk/obsws-python/llms.txt Start, stop, and toggle OBS's virtual camera output. ```APIDOC ## ReqClient — Virtual Camera Start, stop, and toggle OBS's virtual camera output. ### Method: get_virtual_cam_status **Description**: Retrieves the status of the virtual camera. **Returns**: - **output_active** (boolean) - True if the virtual camera is active, false otherwise. ### Method: start_virtual_cam **Description**: Starts the virtual camera. ### Method: toggle_virtual_cam **Description**: Toggles the virtual camera on or off. **Returns**: - **output_active** (boolean) - The new active state of the virtual camera. ### Method: stop_virtual_cam **Description**: Stops the virtual camera. ``` -------------------------------- ### ReqClient — Scene Transitions Source: https://context7.com/aatikturk/obsws-python/llms.txt Manage OBS scene transitions, including listing, getting, setting, and configuring Studio Mode TBar control. ```APIDOC ## ReqClient — Scene Transitions List, get, set, and configure scene transitions including Studio Mode TBar control. ```python import obsws_python as obs with obs.ReqClient() as cl: # List available transition kinds kinds = cl.get_transition_kind_list() print(kinds.transition_kinds) # List all configured transitions transitions = cl.get_scene_transition_list() for t in transitions.transitions: print(t["transitionName"]) # Get/set the active transition current = cl.get_current_scene_transition() print(f"Current: {current.transition_name}, Duration: {current.transition_duration}ms") cl.set_current_scene_transition("Fade") cl.set_current_scene_transition_duration(500) # Update transition settings cl.set_current_scene_transition_settings({"point": 0.5}, overlay=True) # Studio Mode: trigger the transition cl.set_studio_mode_enabled(True) cl.trigger_studio_mode_transition() # TBar manual control (0.0–1.0) cl.set_t_bar_position(0.5, release=False) cl.set_t_bar_position(1.0, release=True) ``` ``` -------------------------------- ### ReqClient - Get Version and Stats Source: https://context7.com/aatikturk/obsws-python/llms.txt Retrieve OBS and plugin version information, or live performance statistics. ```APIDOC ## ReqClient — Version and Stats Retrieve OBS and plugin version information, or live performance statistics. ```python import obsws_python as obs with obs.ReqClient() as cl: version = cl.get_version() print(f"OBS: {version.obs_version}") print(f"WebSocket: {version.obs_web_socket_version}") print(f"RPC version: {version.rpc_version}") stats = cl.get_stats() print(f"FPS: {stats.active_fps}") print(f"CPU usage: {stats.cpu_usage:.1f}%") print(f"Memory: {stats.memory_usage:.0f} MB") print(f"Available disk: {stats.available_disk_space:.0f} MB") ``` ``` -------------------------------- ### Combine ReqClient and EventClient for OBS Automation Source: https://context7.com/aatikturk/obsws-python/llms.txt Use ReqClient to issue commands and EventClient to register callbacks for OBS events. Ensure clients are properly managed using the 'with' statement for resource cleanup. This example rotates through scenes and logs newly created scenes. ```python import time import obsws_python as obs scenes = [] def on_scene_created(data): scenes.append(data.scene_name) print(f"New scene detected: {data.scene_name}") with obs.ReqClient() as req_cl: with obs.EventClient() as evt_cl: evt_cl.callback.register(on_scene_created) # Rotate through all current scenes every 0.5 s resp = req_cl.get_scene_list() for scene in reversed(resp.scenes): req_cl.set_current_program_scene(scene["sceneName"]) time.sleep(0.5) # Wait for any manual scene creation events time.sleep(5) print(f"Scenes created during run: {scenes}") ``` -------------------------------- ### Control Streaming and Recording with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Manage OBS stream and recording outputs, including starting, stopping, pausing, resuming, and querying status. Also includes setting the record directory and creating chapters for Hybrid MP4 recordings. ```python import obsws_python as obs with obs.ReqClient() as cl: # Stream control stream_status = cl.get_stream_status() print(f"Streaming: {stream_status.output_active}") if not stream_status.output_active: cl.start_stream() cl.send_stream_caption("Live caption text") cl.stop_stream() # Record control rec_status = cl.get_record_status() print(f"Recording: {rec_status.output_active}, Paused: {rec_status.output_paused}") cl.start_record() cl.pause_record() cl.resume_record() cl.split_record_file() # Split into a new file cl.create_record_chapter("Act 2") # Hybrid MP4 only (OBS >= 30.2.0) saved = cl.stop_record() print(f"Saved to: {saved.output_path}") # Set record output directory cl.set_record_directory("/home/user/Videos/OBS") ``` -------------------------------- ### Load Connection Info from config.toml and Get OBS Version Source: https://github.com/aatikturk/obsws-python/blob/main/README.md Load connection information from a config.toml file and retrieve the OBS version. Response fields can be accessed as attributes. ```python # load conn info from config.toml cl = obs.ReqClient() # GetVersion, returns a response object resp = cl.get_version() # Access it's field as an attribute print(f"OBS Version: {resp.obs_version}") ``` -------------------------------- ### ReqClient — Streaming and Recording Source: https://context7.com/aatikturk/obsws-python/llms.txt Start, stop, toggle, and query the status of the stream and record outputs. ```APIDOC ## ReqClient — Streaming and Recording Start, stop, toggle, and query the status of the stream and record outputs. ### Method: get_stream_status **Description**: Retrieves the current status of the streaming output. **Returns**: - **output_active** (boolean) - True if streaming is active, false otherwise. ### Method: start_stream **Description**: Starts the streaming output. ### Method: send_stream_caption **Description**: Sends a caption to the stream. **Parameters**: - **caption** (string) - Required - The caption text to send. ### Method: stop_stream **Description**: Stops the streaming output. ### Method: get_record_status **Description**: Retrieves the current status of the recording output. **Returns**: - **output_active** (boolean) - True if recording is active, false otherwise. - **output_paused** (boolean) - True if recording is paused, false otherwise. ### Method: start_record **Description**: Starts the recording output. ### Method: pause_record **Description**: Pauses the recording output. ### Method: resume_record **Description**: Resumes the recording output if it was paused. ### Method: split_record_file **Description**: Splits the current recording file into a new one. ### Method: create_record_chapter **Description**: Creates a chapter marker in the recording (Hybrid MP4 only, OBS >= 30.2.0). **Parameters**: - **chapter_name** (string) - Required - The name of the chapter. ### Method: stop_record **Description**: Stops the recording output. **Returns**: - **output_path** (string) - The path to the saved recording file. ### Method: set_record_directory **Description**: Sets the directory where recordings will be saved. **Parameters**: - **directory** (string) - Required - The path to the desired recording directory. ``` -------------------------------- ### Control Replay Buffer with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Manage the replay buffer output, including starting, stopping, saving, and retrieving the last saved replay file. Ensure the replay buffer is enabled in OBS settings. ```python import obsws_python as obs with obs.ReqClient() as cl: status = cl.get_replay_buffer_status() print(f"Replay buffer active: {status.output_active}") cl.start_replay_buffer() cl.save_replay_buffer() last = cl.get_last_replay_buffer_replay() print(f"Last replay saved to: {last.saved_replay_path}") cl.stop_replay_buffer() ``` -------------------------------- ### ReqClient — Stream Service Settings Source: https://context7.com/aatikturk/obsws-python/llms.txt Get and configure the streaming destination settings, such as RTMP servers and stream keys. ```APIDOC ## ReqClient — Stream Service Settings Get and configure the streaming destination (RTMP, etc.). ```python import obsws_python as obs with obs.ReqClient() as cl: svc = cl.get_stream_service_settings() print(svc.stream_service_type) print(svc.stream_service_settings) # Configure a custom RTMP destination cl.set_stream_service_settings( ss_type="rtmp_custom", ss_settings={ "server": "rtmp://live.twitch.tv/app", "key": "live_XXXXXXXXXXXX", } ) ``` ``` -------------------------------- ### Configure Stream Service Settings with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Get and set the streaming destination settings, such as RTMP server details. Requires specifying the stream service type and its associated settings. ```python import obsws_python as obs with obs.ReqClient() as cl: svc = cl.get_stream_service_settings() print(svc.stream_service_type) print(svc.stream_service_settings) # Configure a custom RTMP destination cl.set_stream_service_settings( ss_type="rtmp_custom", ss_settings={ "server": "rtmp://live.twitch.tv/app", "key": "live_XXXXXXXXXXXX", } ) ``` -------------------------------- ### Send Raw Request Source: https://github.com/aatikturk/obsws-python/blob/main/README.md Use the send method with raw=True to get the raw JSON response data instead of a response object. ```python resp = cl_req.send("GetVersion", raw=True) print(f"response data: {resp}") ``` -------------------------------- ### Get and Deregister Callbacks Source: https://github.com/aatikturk/obsws-python/blob/main/README.md Retrieve a list of currently registered event callbacks and deregister specific callbacks. Both operations accept single functions or lists of functions. ```python # returns a list of currently registered events print(cl.callback.get()) # You may also deregister a callback cl.callback.deregister(on_input_mute_state_changed) ``` -------------------------------- ### Initialize ReqClient with Context Manager Source: https://context7.com/aatikturk/obsws-python/llms.txt Use ReqClient as a context manager for automatic connection cleanup. Provides synchronous request/response messages. ```python import obsws_python as obs with obs.ReqClient(host="localhost", port=4455, password="secret", timeout=3) as cl: # Get OBS and websocket version info resp = cl.get_version() print(f"OBS: {resp.obs_version}, WebSocket: {resp.obs_web_socket_version}") # Access all available attributes print(resp.attrs()) # => ['obs_version', 'obs_web_socket_version', 'rpc_version', 'available_requests', ...] ``` -------------------------------- ### Control Scene Transitions with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Manage scene transitions, including listing, setting, and configuring Studio Mode TBar. Ensure the ReqClient is properly initialized. ```python import obsws_python as obs with obs.ReqClient() as cl: # List available transition kinds kinds = cl.get_transition_kind_list() print(kinds.transition_kinds) # List all configured transitions transitions = cl.get_scene_transition_list() for t in transitions.transitions: print(t["transitionName"]) # Get/set the active transition current = cl.get_current_scene_transition() print(f"Current: {current.transition_name}, Duration: {current.transition_duration}ms") cl.set_current_scene_transition("Fade") cl.set_current_scene_transition_duration(500) # Update transition settings cl.set_current_scene_transition_settings({"point": 0.5}, overlay=True) # Studio Mode: trigger the transition cl.set_studio_mode_enabled(True) cl.trigger_studio_mode_transition() # TBar manual control (0.0–1.0) cl.set_t_bar_position(0.5, release=False) cl.set_t_bar_position(1.0, release=True) ``` -------------------------------- ### Configure Video Settings with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Retrieve and modify OBS video settings, including canvas and output resolution, and frames per second. FPS is calculated as numerator/denominator. ```python import obsws_python as obs with obs.ReqClient() as cl: settings = cl.get_video_settings() # True FPS = fpsNumerator / fpsDenominator fps = settings.fps_numerator / settings.fps_denominator print(f"FPS: {fps}, Base: {settings.base_width}x{settings.base_height}") print(f"Output: {settings.output_width}x{settings.output_height}") # Set to 1080p60 cl.set_video_settings( numerator=60, denominator=1, base_width=1920, base_height=1080, out_width=1920, out_height=1080, ) ``` -------------------------------- ### Manage Profiles and Scene Collections with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Programmatically manage OBS profiles and scene collections. This includes listing, creating, setting current, and removing profiles, as well as setting profile parameters. It also covers listing, creating, and setting current scene collections. ```python import obsws_python as obs with obs.ReqClient() as cl: # Profiles profiles = cl.get_profile_list() print(profiles.profiles) print(f"Current: {profiles.current_profile_name}") cl.create_profile("StreamingProfile") cl.set_current_profile("StreamingProfile") # Profile parameters cl.set_profile_parameter("SimpleOutput", "FilePath", "/home/user/Videos") param = cl.get_profile_parameter("SimpleOutput", "FilePath") print(param.parameter_value) cl.remove_profile("StreamingProfile") # Scene collections cols = cl.get_scene_collection_list() print(cols.scene_collections) cl.create_scene_collection("NewCollection") cl.set_current_scene_collection("NewCollection") ``` -------------------------------- ### Manage Hotkeys with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt List all registered hotkeys and trigger them by name or key sequence. Requires knowledge of OBS hotkey IDs for key sequence triggering. ```python import obsws_python as obs with obs.ReqClient() as cl: # List all hotkey names hotkeys = cl.get_hotkey_list() print(hotkeys.hotkeys) # => ['OBSBasic.StartRecording', 'OBSBasic.StopRecording', ...] # Trigger by name cl.trigger_hotkey_by_name("OBSBasic.StartRecording") # Trigger by key sequence (OBS key IDs from obs-hotkeys.h) cl.trigger_hotkey_by_key_sequence( keyId="OBS_KEY_F5", pressShift=False, pressCtrl=True, pressAlt=False, pressCmd=False, ) ``` -------------------------------- ### ReqClient — Input / Audio Control Source: https://context7.com/aatikturk/obsws-python/llms.txt List inputs, get/set settings, control mute state, volume, balance, sync offset, and audio monitoring. ```APIDOC ## ReqClient — Input / Audio Control List inputs, get/set settings, control mute state, volume, balance, sync offset, and audio monitoring. ### Method: get_input_list **Description**: Lists all available inputs, optionally filtering by kind. **Parameters**: - **input_kind** (string) - Optional - Filters the list to inputs of this specific kind. ### Method: set_input_mute **Description**: Mutes or unmutes a specified input. **Parameters**: - **input_name** (string) - Required - The name of the input. - **muted** (boolean) - Required - Whether to mute the input. ### Method: toggle_input_mute **Description**: Toggles the mute state of a specified input. **Parameters**: - **input_name** (string) - Required - The name of the input. **Returns**: - **input_muted** (boolean) - The new mute state of the input. ### Method: set_input_volume **Description**: Sets the volume for a specified input. **Parameters**: - **input_name** (string) - Required - The name of the input. - **vol_db** (float) - Optional - The volume in decibels. Range: -100 to 26. - **vol_multiplier** (float) - Optional - The volume as a multiplier. Range: 0 to 20. ### Method: get_input_volume **Description**: Gets the current volume of a specified input. **Parameters**: - **input_name** (string) - Required - The name of the input. **Returns**: - **input_volume_db** (float) - The current volume in decibels. ### Method: set_input_audio_balance **Description**: Sets the audio balance for a specified input. **Parameters**: - **input_name** (string) - Required - The name of the input. - **balance** (float) - Required - The audio balance. 0.0 is full left, 1.0 is full right. ### Method: set_input_audio_sync_offset **Description**: Sets the audio sync offset for a specified input. **Parameters**: - **input_name** (string) - Required - The name of the input. - **offset** (integer) - Required - The sync offset in milliseconds. ### Method: set_input_audio_monitor_type **Description**: Sets the audio monitoring type for a specified input. **Parameters**: - **input_name** (string) - Required - The name of the input. - **monitor_type** (string) - Required - The monitoring type (e.g., "OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT"). ### Method: get_input_settings **Description**: Gets the settings for a specified input. **Parameters**: - **input_name** (string) - Required - The name of the input. **Returns**: - **input_settings** (object) - An object containing the input's settings. ### Method: set_input_settings **Description**: Sets the settings for a specified input. **Parameters**: - **input_name** (string) - Required - The name of the input. - **settings** (object) - Required - An object containing the settings to apply. - **overlay** (boolean) - Optional - Whether to overlay the settings or replace them. Defaults to false. ``` -------------------------------- ### Configure OBS WebSocket Connection Source: https://context7.com/aatikturk/obsws-python/llms.txt Connection parameters can be set via a TOML file or keyword arguments. Keyword arguments take precedence. ```toml # ~/config.toml (also searched at ./.config/obsws-python/config.toml) [connection] host = "localhost" port = 4455 password = "mystrongpass" ``` ```python import obsws_python as obs # Uses config.toml automatically if no kwargs provided cl = obs.ReqClient() # Or pass connection info explicitly (overrides config.toml) cl = obs.ReqClient(host="192.168.1.10", port=4455, password="secret", timeout=3) ``` -------------------------------- ### ReqClient - Scene Management Source: https://context7.com/aatikturk/obsws-python/llms.txt Create, remove, rename, list, and switch scenes in OBS. ```APIDOC ## ReqClient — Scene Management Create, remove, rename, list, and switch scenes in OBS. ```python import obsws_python as obs with obs.ReqClient() as cl: # List all scenes resp = cl.get_scene_list() for scene in resp.scenes: print(scene["sceneName"]) # Get/set current program scene current = cl.get_current_program_scene() print(f"Active scene: {current.scene_name}") cl.set_current_program_scene("BRB") # Create and rename a scene cl.create_scene("NewScene") cl.set_scene_name("NewScene", "IntroScene") # Set preview scene (Studio Mode) cl.set_current_preview_scene("IntroScene") # Remove a scene cl.remove_scene("IntroScene") ``` ``` -------------------------------- ### Retrieve OBS Version and Stats Source: https://context7.com/aatikturk/obsws-python/llms.txt Fetch OBS and plugin version information, as well as live performance statistics like FPS, CPU usage, and memory. ```python import obsws_python as obs with obs.ReqClient() as cl: version = cl.get_version() print(f"OBS: {version.obs_version}") print(f"WebSocket: {version.obs_web_socket_version}") print(f"RPC version: {version.rpc_version}") stats = cl.get_stats() print(f"FPS: {stats.active_fps}") print(f"CPU usage: {stats.cpu_usage:.1f}%") print(f"Memory: {stats.memory_usage:.0f} MB") print(f"Available disk: {stats.available_disk_space:.0f} MB") ``` -------------------------------- ### Control Media Inputs with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Control playback of media source inputs, including checking status, seeking, offsetting cursor, and triggering actions like play, pause, restart, and stop. Ensure the media input name is correct. ```python import obsws_python as obs with obs.ReqClient() as cl: # Check media state status = cl.get_media_input_status("VideoClip") print(f"State: {status.media_state}") # e.g. OBS_MEDIA_STATE_PLAYING print(f"Duration: {status.media_duration}ms") print(f"Cursor: {status.media_cursor}ms") # Seek to a position (ms) cl.set_media_input_cursor("VideoClip", 5000) # Offset current cursor position cl.offset_media_input_cursor("VideoClip", offset=1000) # Trigger actions cl.trigger_media_input_action("VideoClip", "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PLAY") cl.trigger_media_input_action("VideoClip", "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PAUSE") cl.trigger_media_input_action("VideoClip", "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_RESTART") cl.trigger_media_input_action("VideoClip", "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_STOP") ``` -------------------------------- ### Connect and Toggle Input Mute Source: https://github.com/aatikturk/obsws-python/blob/main/README.md Instantiate a ReqClient with connection details and toggle the mute state of an input. Connection parameters can be overridden via keyword arguments. ```python import obsws_python as obs # pass conn info if not in config.toml cl = obs.ReqClient(host='localhost', port=4455, password='mystrongpass', timeout=3) # Toggle the mute state of your Mic input cl.toggle_input_mute('Mic/Aux') ``` -------------------------------- ### Manage OBS Scenes Source: https://context7.com/aatikturk/obsws-python/llms.txt Perform operations such as creating, removing, renaming, listing, and switching scenes within OBS. Includes setting the current program and preview scenes. ```python import obsws_python as obs with obs.ReqClient() as cl: # List all scenes resp = cl.get_scene_list() for scene in resp.scenes: print(scene["sceneName"]) # Get/set current program scene current = cl.get_current_program_scene() print(f"Active scene: {current.scene_name}") cl.set_current_program_scene("BRB") # Create and rename a scene cl.create_scene("NewScene") cl.set_scene_name("NewScene", "IntroScene") # Set preview scene (Studio Mode) cl.set_current_preview_scene("IntroScene") # Remove a scene cl.remove_scene("IntroScene") ``` -------------------------------- ### Manage Scene Items with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Control scene items by listing, creating, removing, duplicating, enabling/disabling, locking, reordering, and transforming them. Requires a running OBS instance with WebSocket server enabled. ```python import obsws_python as obs with obs.ReqClient() as cl: # List all items in a scene items = cl.get_scene_item_list("Main") for item in items.scene_items: print(item["sourceName"], item["sceneItemId"]) # Look up an item's numeric ID result = cl.get_scene_item_id("Main", "Webcam") item_id = result.scene_item_id # Enable / disable a scene item cl.set_scene_item_enabled("Main", item_id, enabled=False) cl.set_scene_item_enabled("Main", item_id, enabled=True) # Lock / unlock cl.set_scene_item_locked("Main", item_id, locked=True) # Move item to a specific layer index (0 = bottom) cl.set_scene_item_index("Main", item_id, 0) # Apply a transform (position, scale, crop) cl.set_scene_item_transform("Main", item_id, { "positionX": 0, "positionY": 0, "scaleX": 1.0, "scaleY": 1.0, "cropTop": 0, "cropRight": 0, "cropBottom": 0, "cropLeft": 0, }) # Duplicate a scene item to another scene cl.duplicate_scene_item("Main", item_id, dest_scene_name="Backup") ``` -------------------------------- ### Register Event Callbacks Source: https://github.com/aatikturk/obsws-python/blob/main/README.md Register callback functions for OBS Studio events. Event names are snake_cased and prepended with 'on_'. Callbacks can be registered individually or as a list. ```python # load conn info from config.toml cl = obs.EventClient() def on_scene_created(data): ... # SceneCreated cl.callback.register(on_scene_created) def on_input_mute_state_changed(data): ... # InputMuteStateChanged cl.callback.register(on_input_mute_state_changed) ``` -------------------------------- ### ReqClient — Hotkeys Source: https://context7.com/aatikturk/obsws-python/llms.txt List all registered hotkeys and trigger them by name or key sequence. ```APIDOC ## ReqClient — Hotkeys List all registered hotkeys and trigger them by name or key sequence. ```python import obsws_python as obs with obs.ReqClient() as cl: # List all hotkey names hotkeys = cl.get_hotkey_list() print(hotkeys.hotkeys) # => ['OBSBasic.StartRecording', 'OBSBasic.StopRecording', ...] # Trigger by name cl.trigger_hotkey_by_name("OBSBasic.StartRecording") # Trigger by key sequence (OBS key IDs from obs-hotkeys.h) cl.trigger_hotkey_by_key_sequence( keyId="OBS_KEY_F5", pressShift=False, pressCtrl=True, pressAlt=False, pressCmd=False, ) ``` ``` -------------------------------- ### EventClient: Real-Time Event Subscriptions Source: https://context7.com/aatikturk/obsws-python/llms.txt Connects to OBS and listens for events in a background thread. Callbacks are registered as functions named on_ and receive a typed dataclass with the event's fields. Ensure the main thread stays alive to keep the daemon thread listening. ```python import time import obsws_python as obs class OBSObserver: def __init__(self): self._client = obs.EventClient(host="localhost", port=4455, password="secret") self._client.callback.register([ self.on_current_program_scene_changed, self.on_scene_created, self.on_input_mute_state_changed, self.on_record_state_changed, self.on_exit_started, ]) print(f"Registered events: {self._client.callback.get()}") def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_traceback): self._client.disconnect() def on_current_program_scene_changed(self, data): print(f"Scene changed → {data.scene_name}") def on_scene_created(self, data): print(f"New scene created: {data.scene_name}") def on_input_mute_state_changed(self, data): print(f"{data.input_name} muted={data.input_muted}") def on_record_state_changed(self, data): print(f"Record state: {data.output_state}") def on_exit_started(self, _): print("OBS is shutting down!") if __name__ == "__main__": with OBSObserver() as obs_obs: # Keep main thread alive while daemon thread listens while True: time.sleep(0.1) ``` -------------------------------- ### TOML Configuration for OBS WebSocket Source: https://github.com/aatikturk/obsws-python/blob/main/examples/scene_rotate/README.md Configuration file for connecting to the OBS WebSocket server. Ensure this file is placed in your user home directory. ```toml [connection] host = "localhost" port = 4455 password = "mystrongpass" ``` -------------------------------- ### ReqClient — Profiles and Scene Collections Source: https://context7.com/aatikturk/obsws-python/llms.txt Manage OBS profiles and scene collections programmatically, including creation, selection, and parameter setting. ```APIDOC ## ReqClient — Profiles and Scene Collections Manage OBS profiles and scene collections programmatically. ```python import obsws_python as obs with obs.ReqClient() as cl: # Profiles profiles = cl.get_profile_list() print(profiles.profiles) print(f"Current: {profiles.current_profile_name}") cl.create_profile("StreamingProfile") cl.set_current_profile("StreamingProfile") # Profile parameters cl.set_profile_parameter("SimpleOutput", "FilePath", "/home/user/Videos") param = cl.get_profile_parameter("SimpleOutput", "FilePath") print(param.parameter_value) cl.remove_profile("StreamingProfile") # Scene collections cols = cl.get_scene_collection_list() print(cols.scene_collections) cl.create_scene_collection("NewCollection") cl.set_current_scene_collection("NewCollection") ``` ``` -------------------------------- ### Set Current Program Scene Source: https://github.com/aatikturk/obsws-python/blob/main/README.md Set the current program scene in OBS Studio. ```python # SetCurrentProgramScene cl.set_current_program_scene("BRB") ``` -------------------------------- ### Capture Source Screenshots with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Obtain Base64-encoded screenshots of OBS sources or save them directly to disk. Specify the source name, desired format, and dimensions. ```python import base64 import obsws_python as obs with obs.ReqClient() as cl: # Get screenshot as Base64 string resp = cl.get_source_screenshot( name="Webcam", img_format="png", width=1280, height=720, quality=-1, # -1 = default quality ) img_data = base64.b64decode(resp.image_data.split(",", 1)[1]) with open("webcam_snapshot.png", "wb") as f: f.write(img_data) # Save directly to a file path cl.save_source_screenshot( name="Webcam", img_format="jpeg", file_path="/home/user/snap.jpg", width=640, height=360, quality=80, ) ``` -------------------------------- ### Manage Source Filters with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Perform operations on source filters such as creating, removing, renaming, reordering, configuring, and enabling/disabling. The source name must be specified. ```python import obsws_python as obs with obs.ReqClient() as cl: # List all filters on a source filters = cl.get_source_filter_list("Webcam") for f in filters.filters: print(f["filterName"], f["filterKind"], f["filterEnabled"]) # Create a color correction filter cl.create_source_filter( "Webcam", "ColorFix", "color_filter", {"brightness": 0.1, "contrast": 0.2, "saturation": 0.0} ) # Get/update filter settings info = cl.get_source_filter("Webcam", "ColorFix") print(info.filter_settings) cl.set_source_filter_settings("Webcam", "ColorFix", {"brightness": 0.05}, overlay=True) # Enable / disable filter cl.set_source_filter_enabled("Webcam", "ColorFix", enabled=False) # Reorder filter cl.set_source_filter_index("Webcam", "ColorFix", filter_index=0) # Rename and remove cl.set_source_filter_name("Webcam", "ColorFix", "BrightnessBoost") cl.remove_source_filter("Webcam", "BrightnessBoost") ``` -------------------------------- ### ReqClient — Media Inputs Source: https://context7.com/aatikturk/obsws-python/llms.txt Control playback of media source inputs, including play, pause, stop, and seeking to specific positions. ```APIDOC ## ReqClient — Media Inputs Control playback of media source inputs (play, pause, stop, seek). ```python import obsws_python as obs with obs.ReqClient() as cl: # Check media state status = cl.get_media_input_status("VideoClip") print(f"State: {status.media_state}") # e.g. OBS_MEDIA_STATE_PLAYING print(f"Duration: {status.media_duration}ms") print(f"Cursor: {status.media_cursor}ms") # Seek to a position (ms) cl.set_media_input_cursor("VideoClip", 5000) # Offset current cursor position cl.offset_media_input_cursor("VideoClip", offset=1000) # Trigger actions cl.trigger_media_input_action("VideoClip", "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PLAY") cl.trigger_media_input_action("VideoClip", "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PAUSE") cl.trigger_media_input_action("VideoClip", "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_RESTART") cl.trigger_media_input_action("VideoClip", "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_STOP") ``` ``` -------------------------------- ### ReqClient — Video Settings Source: https://context7.com/aatikturk/obsws-python/llms.txt Retrieve and modify OBS video settings, including canvas and output resolution, and frames per second (FPS). ```APIDOC ## ReqClient — Video Settings Get and set OBS canvas and output resolution along with FPS. ```python import obsws_python as obs with obs.ReqClient() as cl: settings = cl.get_video_settings() # True FPS = fpsNumerator / fpsDenominator fps = settings.fps_numerator / settings.fps_denominator print(f"FPS: {fps}, Base: {settings.base_width}x{settings.base_height}") print(f"Output: {settings.output_width}x{settings.output_height}") # Set to 1080p60 cl.set_video_settings( numerator=60, denominator=1, base_width=1920, base_height=1080, out_width=1920, out_height=1080, ) ``` ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/aatikturk/obsws-python/blob/main/README.md Enable debug logging to view raw messages exchanged with OBS Studio. This requires setting the logging level to DEBUG. ```python import obsws_python as obs import logging logging.basicConfig(level=logging.DEBUG) ... ``` -------------------------------- ### Invoke Vendor Requests with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Invoke custom requests registered by third-party OBS plugins using the vendor extension mechanism. Provide the vendor name, request type, and any necessary request data. ```python import obsws_python as obs with obs.ReqClient() as cl: result = cl.call_vendor_request( vendor_name="my-obs-plugin", request_type="DoSomething", request_data={"param": "value"}, ) print(result.response_data) ``` -------------------------------- ### Write and Read Persistent Data with ReqClient Source: https://context7.com/aatikturk/obsws-python/llms.txt Use ReqClient to write values to OBS's global persistent data slots and read them back. Ensure the realm and slotName are correctly specified. ```python import obsws_python as obs with obs.ReqClient() as cl: # Write a value to the global realm cl.set_persistent_data( realm="OBS_WEBSOCKET_DATA_REALM_GLOBAL", slotName="myApp.lastScene", slotValue="Gaming", ) # Read it back result = cl.get_persistent_data( realm="OBS_WEBSOCKET_DATA_REALM_GLOBAL", slotName="myApp.lastScene", ) print(result.slot_value) # => "Gaming" ``` -------------------------------- ### ReqClient — Source Screenshots Source: https://context7.com/aatikturk/obsws-python/llms.txt Capture screenshots of OBS sources, either as Base64-encoded data or saved directly to a file. ```APIDOC ## ReqClient — Source Screenshots Capture a Base64-encoded screenshot of any OBS source, or save it directly to disk. ```python import base64 import obsws_python as obs with obs.ReqClient() as cl: # Get screenshot as Base64 string resp = cl.get_source_screenshot( name="Webcam", img_format="png", width=1280, height=720, quality=-1, # -1 = default quality ) img_data = base64.b64decode(resp.image_data.split(",", 1)[1]) with open("webcam_snapshot.png", "wb") as f: f.write(img_data) # Save directly to a file path cl.save_source_screenshot( name="Webcam", img_format="jpeg", file_path="/home/user/snap.jpg", width=640, height=360, quality=80, ) ``` ``` -------------------------------- ### ReqClient — Scene Items Source: https://context7.com/aatikturk/obsws-python/llms.txt Manage sources within scenes: list, create, remove, duplicate, enable/disable, lock, reorder, and transform scene items. ```APIDOC ## ReqClient — Scene Items Manage sources within scenes: list, create, remove, duplicate, enable/disable, lock, reorder, and transform scene items. ### Method: get_scene_item_list **Description**: Lists all items in a specified scene. **Parameters**: - **scene_name** (string) - Required - The name of the scene. ### Method: get_scene_item_id **Description**: Looks up an item's numeric ID within a scene. **Parameters**: - **scene_name** (string) - Required - The name of the scene. - **source_name** (string) - Required - The name of the source. ### Method: set_scene_item_enabled **Description**: Enables or disables a scene item. **Parameters**: - **scene_name** (string) - Required - The name of the scene. - **scene_item_id** (integer) - Required - The ID of the scene item. - **enabled** (boolean) - Required - Whether to enable the item. ### Method: set_scene_item_locked **Description**: Locks or unlocks a scene item. **Parameters**: - **scene_name** (string) - Required - The name of the scene. - **scene_item_id** (integer) - Required - The ID of the scene item. - **locked** (boolean) - Required - Whether to lock the item. ### Method: set_scene_item_index **Description**: Moves an item to a specific layer index in a scene. **Parameters**: - **scene_name** (string) - Required - The name of the scene. - **scene_item_id** (integer) - Required - The ID of the scene item. - **index** (integer) - Required - The target layer index (0 = bottom). ### Method: set_scene_item_transform **Description**: Applies a transform (position, scale, crop) to a scene item. **Parameters**: - **scene_name** (string) - Required - The name of the scene. - **scene_item_id** (integer) - Required - The ID of the scene item. - **transform** (object) - Required - An object containing transform properties like positionX, positionY, scaleX, scaleY, cropTop, cropRight, cropBottom, cropLeft. ### Method: duplicate_scene_item **Description**: Duplicates a scene item to another scene. **Parameters**: - **scene_name** (string) - Required - The name of the source scene. - **scene_item_id** (integer) - Required - The ID of the scene item to duplicate. - **dest_scene_name** (string) - Optional - The name of the destination scene. Defaults to the source scene if not provided. ``` -------------------------------- ### ReqClient — Outputs Source: https://context7.com/aatikturk/obsws-python/llms.txt List and control named outputs in OBS, such as virtual cameras or other streaming/recording outputs. ```APIDOC ## ReqClient — Outputs List and control named outputs (beyond the main stream/record). ```python import obsws_python as obs with obs.ReqClient() as cl: outputs = cl.get_output_list() for out in outputs.outputs: print(out["outputName"], out["outputActive"]) status = cl.get_output_status("virtualcam_output") print(f"Active: {status.output_active}") cl.start_output("virtualcam_output") cl.stop_output("virtualcam_output") result = cl.toggle_output("virtualcam_output") print(f"Now active: {result.output_active}") settings = cl.get_output_settings("virtualcam_output") print(settings.output_settings) cl.set_output_settings("virtualcam_output", {"delay": 0}) ``` ``` -------------------------------- ### ReqClient — Filters Source: https://context7.com/aatikturk/obsws-python/llms.txt Control OBS source filters, including creation, removal, renaming, reordering, configuration, and enabling/disabling. ```APIDOC ## ReqClient — Filters Create, remove, rename, reorder, configure, and enable/disable source filters. ```python import obsws_python as obs with obs.ReqClient() as cl: # List all filters on a source filters = cl.get_source_filter_list("Webcam") for f in filters.filters: print(f["filterName"], f["filterKind"], f["filterEnabled"]) # Create a color correction filter cl.create_source_filter( "Webcam", "ColorFix", "color_filter", {"brightness": 0.1, "contrast": 0.2, "saturation": 0.0} ) # Get/update filter settings info = cl.get_source_filter("Webcam", "ColorFix") print(info.filter_settings) cl.set_source_filter_settings("Webcam", "ColorFix", {"brightness": 0.05}, overlay=True) # Enable / disable filter cl.set_source_filter_enabled("Webcam", "ColorFix", enabled=False) # Reorder filter cl.set_source_filter_index("Webcam", "ColorFix", filter_index=0) # Rename and remove cl.set_source_filter_name("Webcam", "ColorFix", "BrightnessBoost") cl.remove_source_filter("Webcam", "BrightnessBoost") ``` ``` -------------------------------- ### ReqClient — Replay Buffer Source: https://context7.com/aatikturk/obsws-python/llms.txt Control the replay buffer output. ```APIDOC ## ReqClient — Replay Buffer Control the replay buffer output. ### Method: get_replay_buffer_status **Description**: Retrieves the status of the replay buffer. **Returns**: - **output_active** (boolean) - True if the replay buffer is active, false otherwise. ### Method: start_replay_buffer **Description**: Starts the replay buffer. ### Method: save_replay_buffer **Description**: Saves the current content of the replay buffer. ### Method: get_last_replay_buffer_replay **Description**: Gets the path to the last saved replay buffer file. **Returns**: - **saved_replay_path** (string) - The file path of the last saved replay. ### Method: stop_replay_buffer **Description**: Stops the replay buffer. ``` -------------------------------- ### Send Raw Requests with ReqClient.send Source: https://context7.com/aatikturk/obsws-python/llms.txt The low-level `send` method allows dispatching raw requests. Setting `raw=True` returns a JSON dict instead of a dataclass object. ```python import obsws_python as obs with obs.ReqClient() as cl: # Default: returns a typed dataclass resp = cl.send("GetVersion") print(resp.obs_version) # raw=True: returns the raw dict raw = cl.send("GetVersion", raw=True) print(raw) # => {'obsVersion': '30.2.0', 'obsWebSocketVersion': '5.5.4', ...} # With request data data = cl.send("GetSceneItemId", {"sceneName": "Main", "sourceName": "Webcam"}) print(data.scene_item_id) ```