Пример #1
0
class QuantumJumpBot:
    def __init__(self, settings):
        self._ws = None
        self.state = BotState(BotState.INITIALIZED)
        self.start_time = time.time()
        self.api = Http()

        self.cm = CogManager()
        self.settings = settings
        self.botconfig = self.settings.Bot
        self.ul = UserList()
        self.room = self.botconfig.roomname
        if self.settings.Bot.debug:
            self.log = QuantumLogger('QuantumJump', self.room, 10)
        else:
            self.log = QuantumLogger('QuantumJump', self.room, 19)

    async def wsend(self, data):
        if type(data) is list:
            data = f"42{json.dumps(data)}"
        elif type(data) is str:
            type_exemptions = ["2probe", "5", "2"]
            if not data.startswith("42") and data not in type_exemptions:
                data = f"42{data}"
        self.log.ws_send(data)

        await self._ws.send(data)

    async def run(self):
        enabled_modules = self.settings.Modules["enabled"]
        self.cm.load_all(enabled_modules, bot=self)
        await self.connect()

    async def disconnect(self):
        self.state = BotState.DISCONNECT
        await self._ws.close()


    async def connect(self):
        logged_in = await self.api.login(self.botconfig.username,
                                          self.botconfig.password)
        async with websockets.connect(
                uri=await self.api.get_wss(),
                timeout=600,
                origin="https://jumpin.chat"
        ) as self._ws:
            self.log.info("Connected to websocket.")
            self.state = BotState.RUNNING
            await self.wsend("2probe")
            async for message in self._ws:
                await self._recv(message=message)

    async def _recv(self, message: str):
        if not message:
            return
        self.log.ws_event(message)

        if message.isdigit():
            return

        if message == "3probe":
            await self.wsend("5")
            roommsg = [
                "room::join",
                {"room": self.botconfig.roomname}
            ]
            await self.wsend(roommsg)
            asyncio.create_task(self.pacemaker())
            # await self.api.enroll()
            return

        data = json.loads(message[2:])

        if data[0] == "room::updateUserList":
            for user in data[1].get("users", []):
                if user:
                    self.ul.add(User(**user))
            if user := data[1].get("user", None):
                if user:
                    self.ul.add(User(**user))
        if data[0] == "room::updateUser":
            self.ul.update(User(**data[1].get("user", None)))

        if data[0] == "room::updateUsers":
            for user in data[1].get("users", []):
                self.ul.update(User(**user))

        # todo  update userlist when a name changes.
        if data[0] == "room::handleChange":
            # ["room::handleChange",{"userId":"5e22c017be8a4900076d3e21","handle":"Tech"}]
            pass
        if data[0] == "room::disconnect":
            self.ul.remove(User(**data[1].get("user", None)))

        if data[0] == "self::join":
            nickmsg = [
                "room::handleChange", {
                    "userId": self.api.login_data.user.get("userId"),
                    "handle": self.botconfig.nickname
                }
            ]
            await self.wsend(nickmsg)
            await self.wsend('42["room::users", {}]')

            # deprecated
            # user_list_data = await self.api.getroominfo(room=str(self.room))
            # self.ul = UserList(**user_list_data)
        if data[0] == "client::error":
            if error := data[1].get("error", False):
                if error == 'ERR_ACCOUNT_REQUIRED':
                    await self.disconnect()
                    raise Exception("Account must be signed in to join this room.")
                if error == 'ENOSESSION':
                    await self.disconnect()
                    raise Exception("Session was invalidated.")
Пример #2
0
class QuantumJumpBot:
    def __init__(self, settings):
        self._ws = None
        self.state = BotState(BotState.INITIALIZED)
        self.start_time = time.time()
        self.api = Http()
        self.cm = CogManager()
        self.settings = settings
        self.botconfig = self.settings.Bot
        self.ul = UserList()
        self.room = self.botconfig.roomname
        if self.settings.Bot.debug:
            self.log = QuantumLogger('QuantumJump', 10)
        else:
            self.log = QuantumLogger('QuantumJump', 19)

    async def wsend(self, data):
        if type(data) is list:
            data = f"42{json.dumps(data)}"
        elif type(data) is str:
            type_exemptions = ["2probe", "5", "2"]
            if not data.startswith("42") and data not in type_exemptions:
                data = f"42{data}"
        await self._ws.send(data)
        self.log.ws_send(data)

    async def run(self):
        enabled_modules = self.settings.Modules["enabled"]
        self.cm.load_all(enabled_modules, bot=self)
        await self.connect()

    async def disconnect(self):
        self.state = BotState.DISCONNECT
        await self._ws.close()

    async def connect(self):
        logged_in = await self.api.login(self.botconfig.username,
                                         self.botconfig.password)
        self.log.info(f"Logged in: {logged_in}")

        async with websockets.connect(
                uri=await self.api.get_wss(),
                timeout=600,
                origin="https://jumpin.chat") as self._ws:
            self.log.info("Connected to websocket.")
            self.state = BotState.RUNNING
            await self.wsend("2probe")
            async for message in self._ws:
                await self._recv(message=message)

    async def _recv(self, message: str):

        if message.isdigit():
            return
        self.log.ws_event(message)

        if message == "3probe":
            await self.wsend("5")
            roommsg = ["room::join", {"room": self.botconfig.roomname}]
            await self.wsend(roommsg)
            asyncio.create_task(self.pacemaker())
            return

        data = json.loads(message[2:])

        if data[0] == "room::status":
            msg = data[1].get("message")
            if "added a video to the playlist" in msg:

                ytid = re.search("(?:v=|\.be\/)(.{11})", msg)[1]
                myid = msg.split(' ')[0]
                title = msg.split('added a video to the playlist: ')[1]
                title = title.split('(https://')[0]

                #data = await self.endpoint(f"https://www.googleapis.com/youtube/v3/videos/?part=snippet%2CcontentDetails%2Cstatistics&id={ytid}",ytid)

                mydb = mysql.connector.connect(
                    host=
                    "gk90usy5ik2otcvi.cbetxkdyhwsb.us-east-1.rds.amazonaws.com",
                    user="******",
                    passwd="n9rgtn2meyhthi9t",
                    database="ppyh9hbf089e36w6")
                cursor = mydb.cursor()

                ids = ((ytid))
                myv = f"SELECT COUNT(*) as count FROM videos WHERE ytid LIKE '{ytid}'"
                add = f"""INSERT INTO videos (ytid, title) VALUES ('{ytid}', '{title}')"""
                our = "SELECT COUNT(*) as count FROM videos"

                cursor.execute(myv)
                myvideos = cursor.fetchone()[0]

                if myvideos == 0:
                    try:
                        cursor.execute(add, ids)
                        mydb.commit()
                        print(f"Added {title} to video.coder.ml/watch/{ytid}.")
                    except:
                        mydb.rollback()

                cursor.execute(our)
                allvids = cursor.fetchone()[0]
                print(f"{allvids} videos in cache.")

                mydb.close()

        if data[0] == "room::updateUserList":
            for user in data[1].get("users", []):
                if user:
                    self.ul.add(User(**user))
            if user := data[1].get("user", None):
                if user:
                    self.ul.add(User(**user))
        if data[0] == "room::updateUser":
            self.ul.update(User(**data[1].get("user", None)))

        if data[0] == "room::updateUsers":
            for user in data[1].get("users", []):
                self.ul.update(User(**user))

        #todo  update userlist when a name changes.
        if data[0] == "room::handleChange":
            # ["room::handleChange",{"userId":"5e22c017be8a4900076d3e21","handle":"Tech"}]
            pass
        if data[0] == "room::disconnect":
            self.ul.remove(User(**data[1].get("user", None)))

        if data[0] == "self::join":
            nickmsg = [
                "room::handleChange", {
                    "userId": self.api.login_data.user.get("userId"),
                    "handle": self.botconfig.nickname
                }
            ]
            await self.wsend(nickmsg)
            await self.wsend('42["room::users", {}]')

            # deprecated
            # user_list_data = await self.api.getroominfo(room=str(self.room))
            # self.ul = UserList(**user_list_data)
        if data[0] == "client::error":
            if error := data[1].get("error", False):
                if error == 'ERR_ACCOUNT_REQUIRED':
                    await self.disconnect()
                    raise Exception(
                        "Account must be signed in to join this room.")
                if error == 'ENOSESSION':
                    await self.disconnect()
                    raise Exception("Session was invalidated.")