Example #1
0
    async def _play(self):
        url = f'wss://play.kahoot.it/cometd/{self.pin}/{self.sessionID}'
        async with aiocometd.Client(url) as client:
            self.socket = client
            await client.subscribe("/service/controller")
            await client.subscribe("/service/player")
            await client.subscribe("/service/status")
            await client.publish(
                '/service/controller', {
                    "host": "kahoot.it",
                    "gameid": self.pin,
                    "captchaToken": self.captchaToken,
                    "name": self.username,
                    "type": "login"
                })
            colors = {0: "RED", 1: "BLUE", 2: "YELLOW", 3: "GREEN"}
            async for rawMessage in client:
                message = rawMessage['data']
                if 'error' in message:
                    raise KahootError(message['description'])
                if 'id' in message:
                    data = json.loads(message['content'])
                    kind = self.lookup[message['id']]
                    if kind == 'START_QUIZ':
                        quizName = data['quizName']
                        self.answers = await self.findAnswers(name=quizName)
                        print(f'ANSWERS RECEIVED')
                    elif kind == 'START_QUESTION':
                        print('------', data['questionIndex'] + 1, '------')
                        if data['gameBlockType'] != 'quiz':
                            pass
                        elif self.answers:
                            correct = self.answers[
                                data['questionIndex']]['index']

                            waitTime = random.uniform(8, 15)
                            print("Waiting", waitTime, "seconds")
                            time.sleep(waitTime)

                            correctChance = random.uniform(0, 10)
                            if (correctChance > 8):
                                answersList = [0, 1, 2, 3]
                                answersList.remove(correct)
                                index = random.randint(0, 3)
                                print(
                                    f'SELECTED {colors[answersList[index]]} (INCORRECT)'
                                )
                                await self.sendAnswer(answersList[index])
                            else:
                                print(f'SELECTED {colors[correct]} (CORRECT)')
                                await self.sendAnswer(correct)
                        else:
                            print('SELECTED FALLBACK')
                            await self.sendAnswer(1)
                    elif kind == 'TIME_UP':
                        pass
                    elif kind == 'RESET_CONTROLLER' or kind == 'GAME_OVER':
                        await client.close()
                        exit()
                    print(kind)
Example #2
0
    async def _connect(self) -> None:
        """Connect to the CometD service and retreive the messages sent by
        the service as long as the client is open
        """
        # connect to the service
        async with aiocometd.Client(self._url, loop=self._loop) as client:
            # set the asynchronous client attribute
            self._client = client
            # subscribe to all the channels
            for subscription in self._subscriptions:
                await client.subscribe(subscription)

            # put the client into a connected state
            self.state = ClientState.CONNECTED
            # listen for incoming messages

            with suppress(futures.CancelledError):
                async for message in client:
                    # emit signal about received messages
                    self._loop.call_soon_threadsafe(self.message_received.emit,
                                                    message)

        # clear the asynchronous client attribute
        self._client = None
        # put the client into a disconnected state
        self.state = ClientState.DISCONNECTED
Example #3
0
    async def _play(self):
        url = f'wss://play.kahoot.it/cometd/{self.pin}/{self.sessionID}'
        async with aiocometd.Client(url, ssl=False) as client:
            self.socket = client
            await client.subscribe("/service/controller")
            await client.subscribe("/service/player")
            await client.subscribe("/service/status")
            await client.publish(
                '/service/controller', {
                    "host": "kahoot.it",
                    "gameid": self.pin,
                    "captchaToken": self.captchaToken,
                    "name": self.username,
                    "type": "login"
                })
            # colors = {0: "RED", 1: "BLUE", 2: "YELLOW", 3: "GREEN"} # assigned but never used wtf?
            offset = 0
            async for rawMessage in client:
                message = rawMessage['data']
                if 'error' in message:
                    raise KahootError(message['description'])
                if 'id' in message:
                    data = json.loads(message['content'])
                    kind = ''
                    if message['id'] in self.lookup:
                        kind = self.lookup[message['id']]

                    if kind == 'START_QUIZ':
                        quizName = data['quizName']
                        quizAnswers = data['quizQuestionAnswers']
                        self.answers = await self.findAnswers(
                            name=quizName, exceptedAnswers=quizAnswers)
                    # print(f'ANSWERS RECEIVED')
                    elif kind == 'START_QUESTION':
                        # print('------', data['questionIndex']+1, '------')
                        if data['gameBlockType'] != 'quiz':
                            pass
                        elif self.answers:
                            correct = self.answers[data['questionIndex'] +
                                                   offset]['index']
                            # print(f'SELECTED {colors[correct]}')
                            await self.sendAnswer(correct)
                        else:
                            # print('SELECTED FALLBACK')
                            await self.sendAnswer(1)
                    elif kind == 'TIME_UP':
                        # print('DID NOT ANSWER IN TIME, SKIPPING TO NEXT ANSWER')
                        # offset += 1
                        pass
                    elif kind == 'RESET_CONTROLLER' or kind == 'GAME_OVER':
                        await client.close()
                        # exit() # WHY THE F**K DOES THIS LIBRARY SHUT DOWN THE WHOLE F*****G PROGRAM WHAT THE F**K
                        return  # WHY COULDN'T IT JUST DO THIS WHAT THE F**K IS WRONG WITH THE ORIGINAL AUTHOR WTF
Example #4
0
    async def _play(self):
        url = f'wss://play.kahoot.it/cometd/{self.pin}/{self.sessionID}'
        async with aiocometd.Client(url, ssl=False) as client:
            self.socket = client
            await client.subscribe("/service/controller")
            await client.subscribe("/service/player")
            await client.subscribe("/service/status")
            await client.publish(
                '/service/controller', {
                    "host": "kahoot.it",
                    "gameid": self.pin,
                    "captchaToken": self.captchaToken,
                    "name": self.username,
                    "type": "login"
                })
            colors = {0: "RED", 1: "BLUE", 2: "YELLOW", 3: "GREEN"}
            offset = 0
            async for rawMessage in client:
                message = rawMessage['data']
                if 'error' in message:
                    raise KahootError(message['description'])
                if 'id' in message:
                    data = json.loads(message['content'])
                    kind = ''
                    if message['id'] in self.lookup:
                        kind = self.lookup[message['id']]

                    if kind == 'START_QUIZ':
                        quizName = data['quizName']
                        self.answers = await self.findAnswers(name=quizName)
                        print(f'ANSWERS RECEIVED')
                    elif kind == 'START_QUESTION':
                        print('------', data['questionIndex'] + 1, '------')
                        if data['gameBlockType'] != 'quiz':
                            pass
                        elif self.answers:
                            correct = self.answers[data['questionIndex'] +
                                                   offset]['index']
                            print(f'SELECTED {colors[correct]}')
                            await self.sendAnswer(correct)
                        else:
                            print('SELECTED FALLBACK')
                            await self.sendAnswer(1)
                    elif kind == 'TIME_UP':
                        print(
                            'DID NOT ANSWER IN TIME, SKIPPING TO NEXT ANSWER')
                        offset += 1
                        pass
                    elif kind == 'RESET_CONTROLLER' or kind == 'GAME_OVER':
                        await client.close()
                        exit()
                    print(kind)
Example #5
0
    async def _setup_connection(self):
        aiocometd.client.DEFAULT_CONNECTION_TYPE = ConnectionType.WEBSOCKET
        streamer_url = self._get_streamer_websocket_url()
        LOGGER.info('Connecting to url: %s', streamer_url)

        auth_extension = AuthExtension(self.get_streamer_token())
        cometd_client = aiocometd.Client(
            streamer_url,
            auth=auth_extension,
        )
        await cometd_client.open()
        await cometd_client.subscribe(dxfeed.DATA_CHANNEL)

        self.cometd_client = cometd_client
        self.logged_in = True
        LOGGER.info('Connected and logged in to dxFeed data stream')

        await self.reset_data_subs()
Example #6
0
    async def _play(self):
        url = f'wss://play.kahoot.it/cometd/{self.pin}/{self.session_id}'
        # pprint(url)
        colors = {0: "RED", 1: "BLUE", 2: "YELLOW", 3: "GREEN"}
        reverse_colors = {'r': 0, 'b': 1, 'y': 2, 'g': 3}
        correct_question_num = None
        async with aiocometd.Client(url, ssl=False) as socket:
            await socket.subscribe('/service/controller')
            await socket.subscribe("/service/status")
            await socket.subscribe("/service/player")
            await self._send(socket, '', 'login', {'name': self.username})
            async for rawMessage in socket:
                message = rawMessage['data']
                if message.get('error'):
                    raise KahootError(
                        f"{message['error']}:{message['description']}")
                if message.get('id') is None:
                    continue
                kind = self.lookup[message['id']]
                message['id'] = kind
                data = json.loads(message['content'])
                if kind == 'START_QUIZ':
                    quizName = data.get(
                        'quizName', data.get('quizTitle'))  # data['quizName']
                    quizAnswers = data['quizQuestionAnswers']
                    self.answers = await self.findAnswers(
                        quizName, quizAnswers)
                    print(f'ANSWERS RECEIVED')
                elif kind == 'GET_READY' and self.random_question:
                    assert self.answers is not None
                    valid_answers = list(
                        filter(lambda x: x['questionIndex'] >= 0,
                               self.answers))
                    for question in self.answers:
                        if question['questionIndex'] >= 0:
                            correct_question_num = question['questionIndex']
                            print(
                                f"{question['questionIndex']} - {question['question']}"
                            )
                        if len(valid_answers) > 1:
                            correct_question_num = int(input('Correct # > '))
                    self.answers[correct_question_num]['questionIndex'] = -1

                elif kind == 'START_QUESTION':
                    assert self.answers is not None
                    if not self.random_question:
                        correct_question_num = data['questionIndex']
                    if data['gameBlockType'] == 'quiz' or self.random_question:
                        correct = self.answers[correct_question_num]
                        if self.random_answer:
                            while True:
                                correct_color = input(
                                    f'Which color is {correct["answer"]}?\n[R/Y/G/B] > '
                                ).lower()[0]
                                if reverse_colors.get(
                                        correct_color) is not None:
                                    correct_index = reverse_colors[
                                        correct_color]
                                    break
                        else:
                            correct_index = correct.get('answerIndex', 0)
                        print(f'SELECTED {colors[correct_index]}')
                        choiceInfo = json.dumps({
                            "type": "quiz",
                            "choice": correct_index,
                            "meta": {
                                "lag": 5000
                            }
                        })
                        await self._send(socket,
                                         choiceInfo,
                                         'message',
                                         params={'id': 45})
                    else:
                        print('Not a quiz question or no answers.')
                elif kind == 'TIME_UP':
                    pass
                    # print(f'DID NOT ANSWER IN TIME ON QUESTION {data["questionNumber"]}')
                elif kind == 'RESET_CONTROLLER' or kind == 'GAME_OVER':
                    break
            try:
                await socket.close()
                exit()
            except asyncio.CancelledError:
                exit()
Example #7
0
 async def _play(self):
     url = f'wss://play.kahoot.it/cometd/{self.pin}/{self.sessionID}'
     async with aiocometd.Client(url, ssl=True) as client:
         self.socket = client
         await client.subscribe("/service/controller")
         await client.subscribe("/service/player")
         await client.subscribe("/service/status")
         await client.publish(
             '/service/controller', {
                 "host": "kahoot.it",
                 "gameid": self.pin,
                 "captchaToken": self.captchaToken,
                 "name": self.nickname,
                 "type": "login"
             })
         offset = 0
         tFADone = 0
         if self.quizID:
             self.answers = await self.findAnswers()
             if self.answers:
                 print(f'ANSWERS RECEIVED')
         async for rawMessage in client:
             message = rawMessage['data']
             if 'error' in message:
                 self.error(message['description'])
             if 'id' in message:
                 data = json.loads(message['content'])
                 kind = ''
                 if message['id'] in self.lookup:
                     kind = self.lookup[message['id']]
                 if kind == 'TWO_FACTOR_AUTH_CORRECT':
                     tFADone = True
                 if kind == 'RESET_TWO_FACTOR_AUTH' and not tFADone:
                     await self.submit2FA()
                 elif kind != 'RESET_TWO_FACTOR_AUTH':
                     print(kind.replace('_', ' '))
                 if kind == 'START_QUIZ':
                     if self.DEBUG:
                         print(data)
                     quizAnswers = data['quizQuestionAnswers']
                     if not self.answers:
                         self.answers = await self.findAnswers(
                             accepted_answers=quizAnswers)
                         if self.answers:
                             print(f'ANSWERS RECEIVED')
                 elif kind == 'START_QUESTION':
                     print('------', data['questionIndex'] + 1, '------')
                     if data['gameBlockType'] not in allowedTypes:
                         pass
                     if self.answers:
                         correct = self.answers[data['questionIndex'] +
                                                offset]['index']
                         print(f'SELECTED {self.colors[int(correct)]}')
                     else:
                         correct = DEFAULT_ANSWER
                         print('SELECTED FALLBACK')
                     await self.sendAnswer(int(correct))
                 elif kind == 'TIME_UP':
                     # print('DID NOT ANSWER IN TIME, SKIPPING TO NEXT ANSWER')
                     # offset += 1
                     pass
                 elif kind == 'RESET_CONTROLLER':
                     print("RESET_CONTROLLER")
                     self.gracefulExit()
                 elif kind == 'GAME_OVER':
                     print(
                         "Game over, if you didn't win the winner has a better bot!"
                     )
                     self.gracefulExit()