Exemplo n.º 1
0
def obs_osc_receive(unused_addr, args, command, value):
    global obs_connected
    if (obs_connected == False):
        obs_connect()
        time.sleep(1)
    if (obs_connected):
        if (command == OBS_COMMAND_SWITCH_SCENE):
            print("Setting scene index : " + str(value))
            ws.call(requests.SetCurrentScene(ScenesNames[value]))
    else:
        print("Warning: OBS not connected. Skipping OBS OSC command")
    print("\n[{0}] ~ {1} {2}".format(args[0], command, value))
 def switch_obs_scene(self):
     current_scene = self.last_set_scene
     target_scene = self.get_target_scene_name()
     # If scene name is assigned to a scene and is not the same scene name as current active scene
     if target_scene not in {"", current_scene}:
         # print(f"Changing scene to {target_scene}")
         self.last_set_scene = target_scene
         if self.connected:
             try:
                 self.ws.call(obsrequest.SetCurrentScene(target_scene))
             except ConnectionResetError:
                 # OBS was closed
                 self.connected = False
Exemplo n.º 3
0
async def event_raw_data(data):
    if DEBUG:
        print("[RAW]", data)

    # Raid Detection
    if not "PRIVMSG" in data:
        if "USERNOTICE" in data and "msg-id=raid" in data:
            mname = re.search('msg-param-displayName\=(.+?);', data)
            mvcnt = re.search('msg-param-viewerCount\=([0-9]+?);', data)
            mid = re.search('msg-param-login\=(.+?);', data)
            print("[RAID]", mname.group(1), "raiding with", mvcnt.group(1),
                  "viewers!!")
            if dat.obsConnected:
                dat.ws.call(
                    obsrequests.SetCurrentScene("raid"))  # OBS scene change
            if dat.raid_autoso:
                print("[RAID] " + mname.group(1) + "(" + mid.group(1) +
                      ") raiding with " + mvcnt.group(1) + " viewers!!")
                if dat.channel != None:
                    if SO_SELF:
                        if USE_TAPI:
                            ci = dat.getChannelInfo(
                                dat.getUIDfromName(mid.group(1)))
                            if ci == None:
                                await dat.channel.send("[shoutout] 不明なユーザー名です")
                            else:
                                if ci['broadcaster_name'] != mname.group(1):
                                    name = ci[
                                        'broadcaster_name'] + "(" + mname.group(
                                            1) + ")"
                                else:
                                    name = mname.group(1)
                                await dat.channel.send(
                                    f"§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§  - - - - - Please check this awesome streamer!! - - - - - - - この素晴らしい配信者もチェックしてください! - -  {name} : https://twitch.tv/{mid.group(1)} 最近の配信 Recent stream : {ci['game_name']} - {ci['title']}  §=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§"
                                )
                        else:
                            if mname.group(1) != mid.group(1):
                                name = mname.group(1) + "(" + mid.group(
                                    1) + ")"
                            else:
                                name = mid.group(1)
                            await dat.channel.send(
                                f"§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§  - - - - - Please check this awesome streamer!! - - - - - - - この素晴らしい配信者もチェックしてください! - -  {name} : https://twitch.tv/{mid.group(1)}  §=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§"
                            )
                    else:
                        await dat.channel.send("!so " + mid.group(1))
                else:
                    print("dat.channel is None.")
            if SOUND and dat.raid_beep:
                simpleaudio.stop_all()
                gBeep.play()
Exemplo n.º 4
0
def TransitionToProgram():
	#Here we check whether StudioMode is on
	StudioState = CheckStudioState()
	#Here we make the transition
	if StudioState == True:
		try:
			CurrentsceneObject = ws.call(requests.GetPreviewScene())
			Currentscene = CurrentsceneObject.getName()
			ws.call(requests.SetCurrentScene(Currentscene))
			print("Sent preview to program")
		except:
			print("Couldn't send preview to program")
	else:
		print("StudioMode not enabled")
Exemplo n.º 5
0
    async def end(self, ctx: Context):
        if not self.bot.check_sender(ctx, 'iarspider'):
            return

        api = self.bot.get_cog("SLCog")
        if not api:
            return

        self.ws.call(obsws_requests.SetCurrentScene('End'))
        try:
            api.roll_credits(self.streamlabs_oauth)
        except requests.HTTPError as exc:
            self.logger.error("Can't roll credits! " + str(exc))
            pass
Exemplo n.º 6
0
    def CambiarEscena(self, opciones):
        """Enviá solicitud de cambiar de Escena."""
        if "escena" in opciones:
            Escena = opciones["escena"]
        else:
            logger.info(f"OBS[Escena no definida]")
            return

        if self.Conectado:
            self.OBS.call(requests.SetCurrentScene(Escena))
            logger.info(f"OBS[Cambiando] {Escena}")
        else:
            logger.warning("OBS[No conectado]")
            self.Notificar("OBS-No-Encontrado")
Exemplo n.º 7
0
def execute_tick(screen_capture, monitor_to_capture, image_mask,
                 image_descriptors, feature_detector, feature_matcher,
                 num_good_matches_required, obs, default_scene_name,
                 target_scene_name, show_debug_window):
    global currently_in_default_scene
    try:
        start_time = time.time()
        frame = numpy.array(
            screen_capture.grab(screen_capture.monitors[monitor_to_capture]))
        masked_frame = cv2.bitwise_and(frame, frame, mask=image_mask)

        image_is_in_frame, matches = frame_contains_one_or_more_matching_images(
            masked_frame, image_mask, image_descriptors, feature_detector,
            feature_matcher, num_good_matches_required, show_debug_window)

        tick_time = None
        if image_is_in_frame:
            if currently_in_default_scene:
                obs.call(requests.SetCurrentScene(target_scene_name))
                tick_time = round(time.time() - start_time, 2)

                currently_in_default_scene = False
        elif not currently_in_default_scene:
            assumed_render_delay_sec = 0.1
            # Compensates for the render delay, otherwise the scene changes too fast
            time.sleep(assumed_render_delay_sec)

            obs.call(requests.SetCurrentScene(default_scene_name))
            tick_time = round(
                (time.time() - start_time) - assumed_render_delay_sec, 2)

            currently_in_default_scene = True
        return (tick_time, matches)
    except Exception as e:
        print(e)
    return (None, -1)
Exemplo n.º 8
0
def switch(bh, msg, scene):
    """Switch OBS scenes"""
    print(scene)
    # Help text
    help = '\n'.join([
        'available scenes: ' + ' '.join('`' + x + '`'
                                        for x in sorted(SCENES.keys())),
        'switch with `switch $NAME`',
    ])
    if not scene or scene not in SCENES:
        return help

    ws.connect()
    # Set the scene
    ws.call(requests.SetCurrentScene(SCENES[scene]))
    # Get current scene and verify it is as expected
    ret = ws.call(requests.GetCurrentScene())
    ws.disconnect()
    # React if it works
    if ret.getName() == SCENES[scene]:
        bh.react(msg, 'check_mark')
Exemplo n.º 9
0
def SwitchScene(BUTTONCONF):
    #Here we check whether StudioMode is on
    StudioState = CheckStudioState()
    if StudioState == True:
        #Here we set the preview scene
        try:
            ws.call(requests.SetPreviewScene(BUTTONCONF["DestinationScene"]))
            print("Set Target to preview")
        except:
            print("Couldn't set Target to preview")
        #These lines are here to change the transition mode when pressing scene button. They produce lag and are commented out
    #	if "Transition" in BUTTONCONF:
    #		if "TransitionDuration" in BUTTONCONF:
    #			SetTransitionMode(BUTTONCONF["Transition"], BUTTONCONF["TransitionDuration"])
    #		else:
    #			SetTransitionMode(BUTTONCONF["Transition"], None)
    #
    #	if "Transition" not in BUTTONCONF:
    #		SetTransitionMode(DefaultTransition, DefaultTransitionDuration)

    else:
        #Here we set the transition specified in config
        if "Transition" in BUTTONCONF:
            if "TransitionDuration" in BUTTONCONF:
                SetTransitionMode(BUTTONCONF["Transition"],
                                  BUTTONCONF["TransitionDuration"])
            else:
                SetTransitionMode(BUTTONCONF["Transition"], None)
        #Here we set the scene being viewed
        try:
            ws.call(requests.SetCurrentScene(BUTTONCONF["DestinationScene"]))
            print("Set " + BUTTONCONF["DestinationScene"] + " to program")
        except:
            print("Couldn't set " + BUTTONCONF["DestinationScene"] +
                  " to program")
        #Here we set back the transition to the defaults
        if "Transition" in BUTTONCONF:
            time.sleep(BUTTONCONF["TransitionDuration"] / 1000 + 0.1)
            SetTransitionMode(DefaultTransition, DefaultTransitionDuration)
Exemplo n.º 10
0
    def switch_obs_scene(self, target_scene: str):
        # Return on empty string
        if not target_scene:
            return

        if target_scene == self.last_set_scene:
            # Last set scene is identical to the current target scene, don't attempt to switch scene
            return

        self.last_set_scene = target_scene
        if not self.connected:
            self.connect()
            if self.connected:
                logger.info(f"Scene switcher connected to OBS websocket")
        if self.connected:
            logger.info(f"Switching scene to '{target_scene}'")
            try:
                self.ws.call(obsrequest.SetCurrentScene(target_scene))
            except (WebSocketConnectionClosedException,
                    ConnectionFailure) as e:
                # OBS was closed
                # logger.exception(f"Error in scene switcher script: {e}")
                pass
Exemplo n.º 11
0
def SwitchScene(Action):
    #Here we check whether StudioMode is on
    StudioState = CheckStudioState()

    if StudioState == True:
        #Here we set the preview scene
        try:
            ws.call(requests.SetPreviewScene(Action["DestinationScene"]))
        except:
            PrintError("Couldn't set " + Action["DestinationScene"] +
                       " to program")
        else:
            PrintWithTime("Set " + Action["DestinationScene"] + " to program")
    else:
        #Here we set the configured transition mode
        if "Transition" in Action:
            Transition_old = GetTransition()
            SetTransition(Action)
        #Here we set the scene being viewed
        try:
            ws.call(requests.SetCurrentScene(Action["DestinationScene"]))
        except:
            PrintError("Couldn't set " + Action["DestinationScene"] +
                       " to program")
        else:
            PrintWithTime("Set " + Action["DestinationScene"] + " to program")
        #Here we set the transition mode back
        if "Transition" in Action:
            try:
                Duration = ws.call(requests.GetTransitionDuration())
                Duration = Duration.getTransitionDuration()
            except:
                PrintError("Couldn't get transition duration")
            else:
                time.sleep(Duration / 1000 + 0.1)
            finally:
                SetTransition(Transition_old)
Exemplo n.º 12
0
def press_button(Button):
    if Button == 8:
        try:
            print("Connecting to Camera1")
            ws.call(requests.SetPreviewScene("Camera1"))
        except:
            print("Exception happened")
    elif Button == 9:
        try:
            print("Connecting to Camera2")
            ws.call(requests.SetPreviewScene("Camera2"))
        except:
            print("Exception happened")
    elif Button == 15:
        try:
            print("Send to stream")
            CurrentsceneObject = ws.call(requests.GetPreviewScene())
            #			print(CurrentsceneObject)
            Currentscene = CurrentsceneObject.getName()
            #			print(Currentscene)
            ws.call(requests.SetCurrentTransition("Fade"))
            ws.call(requests.SetCurrentScene(Currentscene))
        except:
            print("Exception happened")
Exemplo n.º 13
0
def ChooseScene(client, Action):
    Scene = Action["Scene"]
    client.call(requests.SetCurrentScene(Scene))
Exemplo n.º 14
0
def handle(socket, scene: beatoraja.Scene):
    name = config.OBS_SCENES.get(scene, None)
    if name is None or socket.call(obsrequests.GetCurrentScene()).getName() == name:
        return
    socket.call(obsrequests.SetCurrentScene(name))
Exemplo n.º 15
0
duration_min = 5  # Minimum duration we show a scene for before switching
scene_prefix = '_'  # Only auto switch scenes with this prefix
obs_pass = '******'  # Password/secret for OBS-WebSocket
obs_host = 'localhost'  # Hostname of OBS-websocket server, usually localhost
obs_port = 4444  # TCP port that OBS-Webocket server is listening on

logging.basicConfig(level=logging.INFO)
ws = obsws(obs_host, obs_port, obs_pass)
ws.connect()

scenes_all = ws.call(requests.GetSceneList())
scenes_auto = []
last_scene = ''
scene = ''

for s in scenes_all.getScenes():
    if s['name'][0] == scene_prefix:
        print('Added:', s['name'])
        scenes_auto.append(s['name'])

while True:
    while scene == last_scene:
        scene = random.choice(scenes_auto)
    last_scene = scene
    duration = random.randint(duration_min, duration_max)
    print('Switching to [%s] for %ssec...' % (scene, duration))
    ws.call(requests.SetCurrentScene(scene))
    time.sleep(duration)

ws.disconnect()
Exemplo n.º 16
0
 def setScene(self, name):
     self.ws.call(requests.SetCurrentScene(name))
Exemplo n.º 17
0
def ChangeScenes(scene):
    ws.call(requests.SetCurrentScene(scene))
Exemplo n.º 18
0
def scene1(lp, mode):
    ws = obsws("localhost", 4444, "secret")
    ws.connect()
    ws.call(requests.SetCurrentScene("Streamdeck"))
    ws.disconnect()
Exemplo n.º 19
0
import sys
import time

import logging
logging.basicConfig(level=logging.INFO)

sys.path.append('../')
from obswebsocket import obsws, requests  # noqa: E402

host = "localhost"
port = 4444
password = "******"

ws = obsws(host, port, password)
ws.connect()

try:
    scenes = ws.call(requests.GetSceneList())
    for s in scenes.getScenes():
        name = s['name']
        print(u"Switching to {}".format(name))
        ws.call(requests.SetCurrentScene(name))
        time.sleep(2)

    print("End of list")

except KeyboardInterrupt:
    pass

ws.disconnect()
Exemplo n.º 20
0
def scene3(lp, mode):
    ws = obsws("localhost", 4444, "secret")
    ws.connect()
    ws.call(requests.SetCurrentScene("Display 2"))
    ws.disconnect()
Exemplo n.º 21
0
def change_scene(name):
    ws.call(requests.SetCurrentScene(name))   
Exemplo n.º 22
0
            elif "blue" == command:
                b.set_light(['left', 'right'], colors['blue'])

            elif "blue" == command:
                b.set_light(['left', 'right'], colors['red'])

            elif "connect" == command:
                try:
                    ws.connect()
                    bot.send_message('Successfully connected to OBS!')

                except BaseException:
                    bot.send_message('Unable to connect to OBS.')
                continue

            #OBS commands
            #Requires mod permission. (specified in cfg.py)
            try:
                ws.call(requests.SetCurrentScene(command))

            except BaseException:
                print("No scene with that name.")
            #continue

except KeyboardInterrupt:
    print('Terminated by user.')

#ws.call(requests.GetSceneList())
#ws.call(requests.SetCurrentScene(name))
Exemplo n.º 23
0
 def change_scene(self):
     try:
         sel = self.scenes.curselection()[0]
     except IndexError:
         return
     res = self.ws.call(requests.SetCurrentScene(self.scenes.get(sel)))
Exemplo n.º 24
0
 def get(self, scene_name):
     scene = ws.call(requests.GetCurrentScene())
     name = scene.getName()
     if name != scene_name:
         ws.call(requests.SetCurrentScene(scene_name))
Exemplo n.º 25
0
    async def countdown(self, ctx: Context):
        def write_countdown_html():
            args = ctx.message.content.split()[1:]
            parts = tuple(int(x) for x in args[0].split(':'))
            if len(parts) == 2:
                m, s = parts
                m, s = parts
                # noinspection PyShadowingNames
                delta = datetime.timedelta(minutes=m, seconds=s)
                dt = datetime.datetime.now() + delta
            elif len(parts) == 3:
                h, m, s = parts
                dt = datetime.datetime.now().replace(hour=h,
                                                     minute=m,
                                                     second=s)
            else:
                self.botlogger.error("Invalid call to countdown: {0}".format(
                    args[0]))
                return

            self.bot.countdown_to = dt

            with codecs.open(self.htmlfile.replace('html', 'template'),
                             encoding='UTF-8') as f:
                lines = f.read()

            lines = lines.replace('@@date@@', dt.isoformat())
            with codecs.open(self.htmlfile, 'w', encoding='UTF-8') as f:
                f.write(lines)

        if not self.bot.check_sender(ctx, 'iarspider'):
            return

        if not self.ws:
            return

        res: obsws_requests.GetStreamingStatus = self.ws.call(
            obsws_requests.GetStreamingStatus())
        if res.getStreaming():
            self.logger.error('Already streaming!')
            return

        write_countdown_html()

        self.ws.call(obsws_requests.DisableStudioMode())

        # Refresh countdown
        self.ws.call(obsws_requests.SetCurrentScene('Starting'))

        try:
            self.ws.call(
                obsws_requests.SetMute(self.aud_sources.getMic2(), True))
        except KeyError:
            self.logger.warning("[WARN] Can't mute mic-2, please check!")
        self.ws.call(obsws_requests.SetMute(self.aud_sources.getMic1(), True))

        self.ws.call(obsws_requests.EnableStudioMode())

        self.ws.call(obsws_requests.StartStopStreaming())
        time.sleep(1)
        self.ws.call(obsws_requests.PauseRecording())
        # self.get_player()
        # self.player_play_pause()
        self.ws.call(obsws_requests.SetMute(False, 'Радио'))

        asyncio.ensure_future(
            ctx.send('Начат обратный отсчёт до {0}!'.format(
                self.bot.countdown_to.strftime('%X'))))
        asyncio.ensure_future(self.bot.my_run_commercial(self.bot.user_id))

        self.logger.info("Getting Discord cog...")
        discord_bot = self.bot.get_cog('DiscordCog')
        if discord_bot:
            self.logger.info("Got it, requesting announce...")
            asyncio.ensure_future(discord_bot.announce())
        else:
            self.logger.warning("Discord cog not found")
Exemplo n.º 26
0
 def go_brb(self):
     logging.info("OBS command: switch to BRB scene.")
     # self.media_source_toggle()
     return self.ws_call(requests.SetCurrentScene(self.brb_scene))
Exemplo n.º 27
0
 def switch_sequence(self, s):
     # TODO
     self.ws.call(requests.SetCurrentScene(s.scene_name))
Exemplo n.º 28
0
 def go_normal(self):
     logging.info("OBS command: switch to normal scene.")
     self.media_source_toggle()
     return self.ws_call(requests.SetCurrentScene(self.normal_scene))
Exemplo n.º 29
0
 def set_scene(self, scene_name):
     return self.client.call(R.SetCurrentScene(scene_name))
Exemplo n.º 30
0
try:
    #scenes = ws.call(requests.GetSceneList())
    #for s in scenes.getScenes():
    #    name = s['name']
    #    print(u"Switching to {}".format(name))
    #    ws.call(requests.SetCurrentScene(name))
    #    time.sleep(2)
    print("Started Command Processing")
    if command == "Start Streaming Bool":
        if getStreamStatus == False:
            if currentScene == destinationScene:
                print("Already running on the correct scene: Starting Stream")
                ws.call(requests.StartStreaming())
            else:
                print("Setting scene to destination and starting stream")
                ws.call(requests.SetCurrentScene(destinationScene))
                time.sleep(2)
                ws.call(requests.StartStreaming())
        else:
            print("Stream already running. Command halted.")
    elif command == "Stop Stream":
        ws.call(requests.StopStreaming())
    elif command == "Start Stream":
        ws.call(requests.StartStreaming())
    elif command == "Switch Scene":
        if enableOverride == "True" or getStreamStatus == False:
            ws.call(requests.SetCurrentScene(destinationScene))
        elif enableOverride == "False":
            print("Override is not enabled.")  
    
    print("End of list")