async def setup(self): LOGGER.info(f"Running page {self} setup") self.obs_ws = ws = obs.obsws(loop=self.controller.loop) ws.register(self.connection_lost_callback, "Exiting") ws.register(self.recording_started_callback, "RecordingStarted") ws.register(self.recording_paused_callback, "RecordingPaused") ws.register(self.recording_stopped_callback, "RecordingStopping") await self.connect_obs()
async def initialize_obsws(self, ctx): print(f"initializing obs with loop: {self.loop}") self.obs_ws = simpleobsws.obsws( host=os.environ["HOSTNAME"], port=os.environ["PORT"], password=os.environ["PASSWORD"] #loop=self.loop ) self.loop.create_task(self.obs_ws.connect()) return
def set_scene(scene_name): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) ws = simpleobsws.obsws(host='127.0.0.1', port=4444, password='', loop=loop) # Every possible argument has been passed, but none are required. See lib code for defaults. async def make_request(): await ws.connect() # Make the connection to OBS-Websocket data = {'scene-name':scene_name} result = await ws.call('SetCurrentScene', data) # Make a request with the given data print(result) await ws.disconnect() # Clean things up by disconnecting. Only really required in a few specific situations, but good practice if you are done making requests or listening to events. loop.run_until_complete(make_request())
def __init__(self): self.start_time = datetime.utcnow() self.command_timeouts = {} self.timer = {'semaphore': Semaphore(), 'time': datetime.utcnow()} super(TwitchBot, self).__init__(irc_token=password, client_id=client_id, client_secret=secret, nick=nickname, prefix=prefix, initial_channels=active_channels) self.obs_websocket = obsws(host=obs_address, port=obs_port, password=obs_password, loop=self.loop)
async def connect_and_send(rr): # NOTE: User has to edit host, port, and password. try: import simpleobsws except ModuleNotFoundError: import sys sys.stderr.write( 'Error: This script requires a module simpleobsws (https://github.com/IRLToolkit/simpleobsws).\n' ) sys.exit(1) ws = simpleobsws.obsws(host='127.0.0.1', port=4444, password=None, loop=loop) await ws.connect() for req, data in rr: print('req="%s" data=%s' % (str(req), str(data))) if req == 'sleep': await asyncio.sleep(data) else: res = await ws.call(req, data) print(json.dumps(res, indent="\t")) await ws.disconnect()
import asyncio import json import simpleobsws import aiohttp from aiohttp import web httpAddress = '0.0.0.0' httpPort = 4445 httpAuthKey = None wsAddress = '127.0.0.1' wsPort = 4444 loop = asyncio.get_event_loop() ws = simpleobsws.obsws(host=wsAddress, port=wsPort, loop=loop) def statusmessage(message): print(str(message) + '... ', end='', flush=True) async def handle_emit_request(request): """Handler function for all emit-based HTTP requests. Assumes that you know what you are doing because it will never return an error.""" if ('AuthKey' not in request.headers) and httpAuthKey != None: return web.json_response({ 'status': 'error', 'error': 'AuthKey header is required.' }) if httpAuthKey == None or (request.headers['AuthKey'] == httpAuthKey): requesttype = request.match_info['type'] try: requestdata = await request.json() except json.decoder.JSONDecodeError:
#!/usr/bin/env python import asyncio import simpleobsws from i3ipc.aio import Connection from i3ipc import Event import config as cfg loop = asyncio.get_event_loop() ws = simpleobsws.obsws( host=cfg.host, port=cfg.port, password=cfg.password, loop=loop ) # Every possible argument has been passed, but none are required. See lib code for defaults. async def make_request(): i3 = await Connection().connect() await ws.connect() # Make the connection to OBS-Websocket i3.on(Event.WORKSPACE_FOCUS, on_workspace_focus) async def set_source_visibility(source, visibility): data = {'source': source, 'render': visibility} result = await ws.call('SetSceneItemRender', data) return result async def on_workspace_focus(self, event): if event.current.name in cfg.allowed_workspaces: result = await set_source_visibility(cfg.source, True) else: result = await set_source_visibility(cfg.source, False)
scoring = create_connection(scoringuri) except: print( "Could not connect to the scoring software. Verify the address and try again." ) raise SystemExit(0) print("Connected to the scoring software") # Declare the asyncio loop for interacting with OBS loop = asyncio.get_event_loop() # Create the OBS socket. if (args.pw): obs = simpleobsws.obsws(host=args.obs, port=args.port, password=args.pw, loop=loop) else: obs = simpleobsws.obsws(host=args.obs, port=args.port, loop=loop) # Main loop. async def run(): # Connect to the OBS socket. try: await obs.connect() except: print( "Could not connect to OBS. Make sure you have the OBS websocket plugin installed and try again." ) raise SystemExit(0)
import asyncio import simpleobsws loop = asyncio.get_event_loop() ws = simpleobsws.obsws(host='127.0.0.1', port=4444, password='******', loop=loop) # Every possible argument has been passed, but none are required. See lib code for defaults. async def make_request(): await ws.connect() # Make the connection to OBS-Websocket result = await ws.call('GetVersion') # We get the current OBS version. More request data is not required print(result) # Print the raw json output of the GetVersion request await asyncio.sleep(1) data = {'source':'test_source', 'volume':0.5} result = await ws.call('SetVolume', data) # Make a request with the given data print(result) await ws.disconnect() # Clean things up by disconnecting. Only really required in a few specific situations, but good practice if you are done making requests or listening to events. loop.run_until_complete(make_request())
#!/usr/bin/env python import asyncio import simpleobsws import time loop = asyncio.get_event_loop() ws = simpleobsws.obsws( host='127.0.0.1', port=4444 ) # Every possible argument has been passed, but none are required. See lib code for defaults. async def stop_recording(): await ws.connect() # Make the connection to OBS-Websocket retry_count = 0 while True: result = await ws.call('StopRecording') print(result) if result['status'] == 'ok': break retry_count = retry_count + 1 if retry_count == 10: break time.sleep(0.5) await ws.disconnect( ) # Clean things up by disconnecting. Only really required in a few specific situations, but good practice if you are done making requests or listening to events. loop.run_until_complete(stop_recording())
return web.Response(text="Hello, world") @routes.post("/setscene") async def setscene(request): print("post started!") req = await request.json() if "scene" not in req: return web.Response(text="Need payload {scene:sceneyouwant}", status=400) scene = req["scene"] result = await ws.call("SetCurrentScene", {"scene-name": scene}) print(result) scene = "test" return web.Response(text=f"Set scene to {scene}") async def on_startup(app): await ws.connect() async def on_cleanup(app): await ws.disconnect() if __name__ == "__main__": app = web.Application() app.add_routes(routes) app.on_startup.append(on_startup) ws = simpleobsws.obsws(host="127.0.0.1", port=4444) web.run_app(app, port=5000)
config = ConfigParser() config.read('config.ini') httpAddress = config.get('http', 'bind_to_address') httpPort = config.getint('http', 'bind_to_port') httpAuthKey = config.get('http', 'authentication_key') if httpAuthKey == '': print('Starting HTTP server without authentication.') httpAuthKey = None else: print('Starting HTTP server with AuthKey set to "{}"'.format(httpAuthKey)) wsAddress = config.get('obsws', 'ws_address') wsPort = config.getint('obsws', 'ws_port') wsPassword = config.get('obsws', 'ws_password') loop = asyncio.get_event_loop() ws = simpleobsws.obsws(host=wsAddress, port=wsPort, password=wsPassword, loop=loop) def statusmessage(message): print(str(message) + '... ', end='', flush=True) async def handle_emit_request(request): """Handler function for all emit-based HTTP requests. Assumes that you know what you are doing because it will never return an error.""" if ('AuthKey' not in request.headers) and httpAuthKey != None: return web.json_response({ 'status': 'error', 'error': 'AuthKey header is required.' }) if httpAuthKey == None or (request.headers['AuthKey'] == httpAuthKey):
# returning data to track as previous return data logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) async def forever(): # dict for keeping track of the previous data we sent to obs previous = { "item": source_name, "crop": {"bottom": 0, "left": 0, "right": 0, "top": 0}, "visible": False, "position": {"y": 0, "x": 0}, "scale": {"y": 1.0, "x": 1.0}, } # your infinite loop here, for example: await ws.connect() while True: previous = await main_loop(previous) sleep(0.50) await ws.disconnect() # now for the OBS stuff loop = asyncio.get_event_loop() ws = simpleobsws.obsws(host=obs_host, port=obs_port, password=obs_password, loop=loop) loop.run_until_complete(forever())
def get_ws_and_loop(): loop = get_event_loop() return obsws(host=obs_address, port=obs_port, password=obs_password), loop
import asyncio import simpleobsws import json import sys import getopt loop = asyncio.get_event_loop() ws = simpleobsws.obsws(host='127.0.0.1', port=4444, loop=loop) async def get_midi_scenes(): '''return a json with all OBS scenes containing sources with "MIDI" in their name ''' midiscenes = json.loads("{\"names\":[]}") data = {} result = await ws.call('GetSceneList', data) # Make a request with the given data scenes = result["scenes"] for scene in scenes: sources = scene["sources"] sourcenames = list(map(lambda source: source['name'], sources)) midisources = list(filter(lambda source: ("MIDI" in source), sourcenames)) if len(midisources) > 0: midiscenes["names"].append(scene["name"]) return midiscenes async def send_request(request, data): '''send data message to all scenes containing sources with "MIDI" in their name
import asyncio import simpleobsws loop = asyncio.new_event_loop() obs = simpleobsws.obsws(loop=loop) request_map = { 'change_scene': 'SetCurrentScene', 'toggle_recording': 'StartStopRecording', 'toggle_streaming': 'StartStopStreaming' } def handle_action(logger, view_handler, action_config): return loop.run_until_complete( handle_action_async(logger, view_handler, action_config)) def get_request_dictionary(action_config): if action_config['request'] == 'change_scene': return {'scene-name': action_config['scene']} else: return {} async def handle_action_async(logger, view_handler, action_config): await obs.connect() request = request_map.get(action_config['request']) request_data = get_request_dictionary(action_config) await obs.call(request, data=request_data) await obs.disconnect() return 'success'