def __init__(
        self,
        languageEntry: LanguageEntry,
        definition: str,
        englishExample: str,
        foreignExample: str,
        languageName: str,
        transliteration: str,
        word: str
    ):
        if languageEntry is None:
            raise ValueError(f'languageEntry argument is malformed: \"{languageEntry}\"')
        elif not utils.isValidStr(definition):
            raise ValueError(f'definition argument is malformed: \"{definition}\"')
        elif not utils.isValidStr(languageName):
            raise ValueError(f'languageName argument is malformed: \"{languageName}\"')
        elif not utils.isValidStr(word):
            raise ValueError(f'word argument is malformed: \"{word}\"')

        self.__languageEntry = languageEntry
        self.__definition = definition
        self.__englishExample = englishExample
        self.__foreignExample = foreignExample
        self.__languageName = languageName
        self.__transliteration = transliteration
        self.__word = word
示例#2
0
    def validateAndRefreshAccessToken(self, twitchClientId: str,
                                      twitchClientSecret: str,
                                      twitchHandle: str):
        if not utils.isValidStr(twitchClientId):
            raise ValueError(
                f'twitchClientId argument is malformed: \"{twitchClientId}\"')
        elif not utils.isValidStr(twitchClientSecret):
            raise ValueError(
                f'twitchClientSecret argument is malformed: \"{twitchClientSecret}\"'
            )
        elif not utils.isValidStr(twitchHandle):
            raise ValueError(
                f'twitchHandle argument is malformed: \"{twitchHandle}\"')

        print(
            f'Validating Twitch access token for \"{twitchHandle}\"... ({utils.getNowTimeText(includeSeconds = True)})'
        )

        rawResponse = None
        try:
            rawResponse = requests.get(
                url=self.__oauth2ValidateUrl,
                params={
                    'Authorization':
                    f'OAuth {self.getAccessToken(twitchHandle)}'
                },
                timeout=utils.getDefaultTimeout())
        except (ConnectionError, HTTPError, MaxRetryError, NewConnectionError,
                Timeout) as e:
            print(
                f'Exception occurred when attempting to validate Twitch access token: {e}'
            )
            raise RuntimeError(
                f'Exception occurred when attempting to validate Twitch access token: {e}'
            )

        jsonResponse = None
        try:
            jsonResponse = rawResponse.json()
        except JSONDecodeError as e:
            print(
                f'Exception occurred when attempting to decode Twitch\'s response into JSON: {e}'
            )
            raise RuntimeError(
                f'Exception occurred when attempting to decode Twitch\'s response into JSON: {e}'
            )

        if jsonResponse.get('client_id') is None or len(
                jsonResponse['client_id']) == 0:
            print(
                f'Requesting new Twitch tokens for \"{twitchHandle}\"... ({utils.getNowTimeText(includeSeconds = True)})'
            )

            self.__refreshTokens(twitchClientId=twitchClientId,
                                 twitchClientSecret=twitchClientSecret,
                                 twitchHandle=twitchHandle)
        else:
            print(
                f'No need to request new Twitch tokens for \"{twitchHandle}\" ({utils.getNowTimeText(includeSeconds = True)})'
            )
示例#3
0
    def __init__(self,
                 eventLoop: AbstractEventLoop,
                 client: Client,
                 port: int,
                 webhookSecret: str,
                 timber: Timber,
                 callbackRoute: str = '/callback'):
        if eventLoop is None:
            raise ValueError(
                f'eventLoop argument is malformed: \"{eventLoop}\"')
        elif client is None:
            raise ValueError(f'client argument is malformed: \"{client}\"')
        elif not utils.isValidNum(port):
            raise ValueError(f'port argument is malformed: \"{port}\"')
        elif port <= 100:
            raise ValueError(f'port argument is out of bounds: {port}')
        elif not utils.isValidStr(webhookSecret):
            raise ValueError(
                f'webhookSecret argument is malformed: \"{webhookSecret}\"')
        elif timber is None:
            raise ValueError(f'timber argument is malformed: \"{timber}\"')
        elif not utils.isValidStr(callbackRoute):
            raise ValueError(
                f'callbackRoute argument is malformed: \"{callbackRoute}\"')

        self.__eventLoop: AbstractEventLoop = eventLoop
        self.__port: int = port
        self.__timber: Timber = timber

        self.__isStarted: bool = False
        self.__eventSubClient: EventSubClient = EventSubClient(
            client=client,
            webhook_secret=webhookSecret,
            callback_route=callbackRoute)
示例#4
0
    async def handleEvent(self, twitchChannel: Channel, twitchUser: User,
                          tags: Dict[str, Any]) -> bool:
        if twitchChannel is None:
            raise ValueError(
                f'twitchChannel argument is malformed: \"{twitchChannel}\"')
        elif twitchUser is None:
            raise ValueError(
                f'twitchUser argument is malformed: \"{twitchUser}\"')
        elif tags is None:
            raise ValueError(f'tags argument is malformed: \"{tags}\"')

        if not twitchUser.isChatLoggingEnabled():
            return False

        raidedByName = tags.get('msg-param-displayName')
        if not utils.isValidStr(raidedByName):
            raidedByName = tags.get('display-name')
        if not utils.isValidStr(raidedByName):
            raidedByName = tags.get('login')

        if not utils.isValidStr(raidedByName):
            self.__timber.log(
                'RaidLogEvent',
                f'{twitchUser.getHandle()} was raided, but the tags dictionary seems to have strange values: {tags}'
            )
            return False

        raidSize = utils.getIntFromDict(tags, 'msg-param-viewerCount', 0)

        self.__chatLogger.logRaid(raidSize=raidSize,
                                  fromWho=raidedByName,
                                  twitchChannel=twitchChannel)

        return True
示例#5
0
    async def handlePointRedemption(self, twitchChannel: Channel,
                                    twitchUser: User, redemptionMessage: str,
                                    rewardId: str, userIdThatRedeemed: str,
                                    userNameThatRedeemed: str) -> bool:
        if twitchChannel is None:
            raise ValueError(
                f'twitchChannel argument is malformed: \"{twitchChannel}\"')
        elif twitchUser is None:
            raise ValueError(
                f'twitchUser argument is malformed: \"{twitchUser}\"')
        elif not utils.isValidStr(rewardId):
            raise ValueError(f'rewardId argument is malformed: \"{rewardId}\"')
        elif not utils.isValidStr(userIdThatRedeemed):
            raise ValueError(
                f'userIdThatRedeemed argument is malformed: \"{userIdThatRedeemed}\"'
            )
        elif not utils.isValidStr(userNameThatRedeemed):
            raise ValueError(
                f'userNameThatRedeemed argument is malformed: \"{userNameThatRedeemed}\"'
            )

        generalSettings = await self.__generalSettingsRepository.getAllAsync()

        if not generalSettings.isTriviaGameEnabled():
            return False
        elif not twitchUser.isTriviaGameEnabled():
            return False

        secondsToLive = generalSettings.getWaitForTriviaAnswerDelay()
        if twitchUser.hasWaitForTriviaAnswerDelay():
            secondsToLive = twitchUser.getWaitForTriviaAnswerDelay()

        points = generalSettings.getTriviaGamePoints()
        if twitchUser.hasTriviaGamePoints():
            points = twitchUser.getTriviaGamePoints()

        triviaFetchOptions = TriviaFetchOptions(
            twitchChannel=twitchUser.getHandle(),
            isJokeTriviaRepositoryEnabled=twitchUser.
            isJokeTriviaRepositoryEnabled(),
            questionAnswerTriviaConditions=QuestionAnswerTriviaConditions.
            NOT_ALLOWED)

        self.__triviaGameMachine.submitAction(
            StartNewTriviaGameAction(pointsForWinning=points,
                                     secondsToLive=secondsToLive,
                                     twitchChannel=twitchUser.getHandle(),
                                     userId=userIdThatRedeemed,
                                     userName=userNameThatRedeemed,
                                     triviaFetchOptions=triviaFetchOptions))

        self.__timber.log(
            'TriviaGameRedemption',
            f'Redeemed trivia game for {userNameThatRedeemed}:{userIdThatRedeemed} in {twitchUser.getHandle()}'
        )
        return True
示例#6
0
    async def handlePointRedemption(self, twitchChannel: Channel,
                                    twitchUser: User, redemptionMessage: str,
                                    rewardId: str, userIdThatRedeemed: str,
                                    userNameThatRedeemed: str) -> bool:
        if twitchChannel is None:
            raise ValueError(
                f'twitchChannel argument is malformed: \"{twitchChannel}\"')
        elif twitchUser is None:
            raise ValueError(
                f'twitchUser argument is malformed: \"{twitchUser}\"')
        elif not utils.isValidStr(rewardId):
            raise ValueError(f'rewardId argument is malformed: \"{rewardId}\"')
        elif not utils.isValidStr(userIdThatRedeemed):
            raise ValueError(
                f'userIdThatRedeemed argument is malformed: \"{userIdThatRedeemed}\"'
            )
        elif not utils.isValidStr(userNameThatRedeemed):
            raise ValueError(
                f'userNameThatRedeemed argument is malformed: \"{userNameThatRedeemed}\"'
            )

        self.__timber.log(
            'PotdPointRedemption',
            f'Fetching Pic Of The Day for {userNameThatRedeemed}:{userIdThatRedeemed} in {twitchUser.getHandle()}...'
        )

        try:
            picOfTheDay = await twitchUser.fetchPicOfTheDay()
            await twitchUtils.safeSend(
                twitchChannel,
                f'@{userNameThatRedeemed} here\'s the POTD: {picOfTheDay}')
            self.__timber.log(
                'PotdPointRedemption',
                f'Redeemed Pic Of The Day for {userNameThatRedeemed}:{userIdThatRedeemed} in {twitchUser.getHandle()}'
            )
            return True
        except FileNotFoundError as e:
            self.__timber.log(
                'PotdPointRedemption',
                f'Tried to redeem Pic Of The Day for {userNameThatRedeemed}:{userIdThatRedeemed} in {twitchUser.getHandle()}, but the POTD file is missing: {e}'
            )
            await twitchUtils.safeSend(
                twitchChannel,
                f'⚠ Pic Of The Day file for {twitchUser.getHandle()} is missing'
            )
        except ValueError as e:
            self.__timber.log(
                'PotdPointRedemption',
                f'Tried to redeem Pic Of The Day for {userNameThatRedeemed}:{userIdThatRedeemed} in {twitchUser.getHandle()}, but the POTD content is malformed: {e}'
            )
            await twitchUtils.safeSend(
                twitchChannel,
                f'⚠ Pic Of The Day content for {twitchUser.getHandle()} is malformed'
            )

        return False
示例#7
0
    async def handlePointRedemption(self, twitchChannel: Channel,
                                    twitchUser: User, redemptionMessage: str,
                                    rewardId: str, userIdThatRedeemed: str,
                                    userNameThatRedeemed: str) -> bool:
        if twitchChannel is None:
            raise ValueError(
                f'twitchChannel argument is malformed: \"{twitchChannel}\"')
        elif twitchUser is None:
            raise ValueError(
                f'twitchUser argument is malformed: \"{twitchUser}\"')
        elif not utils.isValidStr(rewardId):
            raise ValueError(f'rewardId argument is malformed: \"{rewardId}\"')
        elif not utils.isValidStr(userIdThatRedeemed):
            raise ValueError(
                f'userIdThatRedeemed argument is malformed: \"{userIdThatRedeemed}\"'
            )
        elif not utils.isValidStr(userNameThatRedeemed):
            raise ValueError(
                f'userNameThatRedeemed argument is malformed: \"{userNameThatRedeemed}\"'
            )

        if not twitchUser.isPkmnEnabled():
            return False

        splits = utils.getCleanedSplits(redemptionMessage)
        if not utils.hasItems(splits):
            await twitchUtils.safeSend(
                twitchChannel,
                f'⚠ Sorry @{userNameThatRedeemed}, you must specify the exact user name of the person you want to fight'
            )
            return False

        opponentUserName = utils.removePreceedingAt(splits[0])
        generalSettings = await self.__generalSettingsRepository.getAllAsync()
        actionCompleted = False

        if generalSettings.isFuntoonApiEnabled():
            if await self.__funtoonRepository.pkmnBattle(
                    userThatRedeemed=userNameThatRedeemed,
                    userToBattle=opponentUserName,
                    twitchChannel=twitchUser.getHandle()):
                actionCompleted = True

        if not actionCompleted and generalSettings.isFuntoonTwitchChatFallbackEnabled(
        ):
            await twitchUtils.safeSend(
                twitchChannel,
                f'!battle {userNameThatRedeemed} {opponentUserName}')
            actionCompleted = True

        self.__timber.log(
            'PkmnBattleRedemption',
            f'Redeemed pkmn battle for {userNameThatRedeemed}:{userIdThatRedeemed} in {twitchUser.getHandle()}'
        )
        return actionCompleted
示例#8
0
    def setNonce(self, key: str, nonce: str):
        if not utils.isValidStr(key):
            raise ValueError(f'key argument is malformed: \"{key}\"')

        if not utils.isValidStr(nonce):
            print(f'key \"{key}\" has an invalid nonce: \"{nonce}\"')
            self.__cache.pop(key, None)
            return

        key = key.lower()
        self.__cache[key] = nonce
示例#9
0
    async def handleEvent(self, twitchChannel: Channel, twitchUser: User,
                          tags: Dict[str, Any]) -> bool:
        if twitchChannel is None:
            raise ValueError(
                f'twitchChannel argument is malformed: \"{twitchChannel}\"')
        elif twitchUser is None:
            raise ValueError(
                f'twitchUser argument is malformed: \"{twitchUser}\"')
        elif tags is None:
            raise ValueError(f'tags argument is malformed: \"{tags}\"')

        generalSettings = await self.__generalSettingsRepository.getAllAsync()

        if not generalSettings.isRaidLinkMessagingEnabled():
            return False
        elif not twitchUser.isRaidLinkMessagingEnabled():
            return False

        raidedByName = tags.get('msg-param-displayName')
        if not utils.isValidStr(raidedByName):
            raidedByName = tags.get('display-name')
        if not utils.isValidStr(raidedByName):
            raidedByName = tags.get('login')

        if not utils.isValidStr(raidedByName):
            self.__timber.log(
                'RaidEvent',
                f'{twitchUser.getHandle()} was raided, but the tags dictionary seems to have strange values: {tags}'
            )
            return False

        messageSuffix = f'😻 Raiders, if you could, I\'d really appreciate you clicking this link to watch the stream. It helps me on my path to partner. {twitchUser.getTwitchUrl()} Thank you! ✨'
        raidSize = utils.getIntFromDict(tags, 'msg-param-viewerCount', -1)

        message: str = None
        if raidSize >= 10:
            raidSizeStr = locale.format_string("%d", raidSize, grouping=True)
            message = f'Thank you for the raid of {raidSizeStr} {raidedByName}! {messageSuffix}'
        else:
            message = f'Thank you for the raid {raidedByName}! {messageSuffix}'

        delaySeconds = generalSettings.getRaidLinkMessagingDelay()

        self.__eventLoop.create_task(
            twitchUtils.waitThenSend(messageable=twitchChannel,
                                     delaySeconds=delaySeconds,
                                     message=message))

        self.__timber.log(
            'RaidEvent',
            f'{twitchUser.getHandle()} received raid of {raidSize} from {raidedByName}!'
        )
        return True
示例#10
0
    def getRefreshToken(self, twitchHandle: str) -> str:
        if not utils.isValidStr(twitchHandle):
            raise ValueError(
                f'twitchHandle argument is malformed: \"{twitchHandle}\"')

        jsonContents = self.__readJson(twitchHandle)
        refreshToken = jsonContents['refreshToken']

        if not utils.isValidStr(refreshToken):
            raise ValueError(
                f'\"refreshToken\" value in \"{self.__twitchTokensFile}\" is malformed: \"{refreshToken}\"'
            )

        return refreshToken
    def getLocation(self, locationId: str) -> Location:
        if not utils.isValidStr(locationId):
            raise ValueError(
                f'locationId argument is malformed: \"{locationId}\"')

        if locationId.lower() in self.__locationsCache:
            return self.__locationsCache[locationId.lower()]

        jsonContents = self.__readJson()

        for locationId in jsonContents:
            if locationId.lower() == locationId.lower():
                timeZoneStr = jsonContents[locationId]['timeZone']
                timeZone = self.__timeZoneRepository.getTimeZone(timeZoneStr)

                location = Location(latitude=jsonContents[locationId]['lat'],
                                    longitude=jsonContents[locationId]['lon'],
                                    locationId=locationId,
                                    name=jsonContents[locationId]['name'],
                                    timeZone=timeZone)

                self.__locationsCache[locationId.lower()] = location
                return location

        raise RuntimeError(
            f'Unable to find location with ID \"{locationId}\" in locations file: \"{self.__locationsFile}\"'
        )
示例#12
0
    def getSuperTriviaCorrectAnswerReveal(
        self,
        question: AbsTriviaQuestion,
        newCuteness: CutenessResult,
        multiplier: int,
        points: int,
        userName: str,
        delimiter: str = '; '
    ) -> str:
        if question is None:
            raise ValueError(f'question argument is malformed: \"{question}\"')
        elif newCuteness is None:
            raise ValueError(f'newCuteness argument is malformed: \"{newCuteness}\"')
        elif not utils.isValidNum(multiplier):
            raise ValueError(f'multiplier argument is malformed: \"{multiplier}\"')
        elif not utils.isValidNum(points):
            raise ValueError(f'points argument is malformed: \"{points}\"')
        elif not utils.isValidStr(userName):
            raise ValueError(f'userName argument is malformed: \"{userName}\"')
        elif delimiter is None:
            raise ValueError(f'delimiter argument is malformed: \"{delimiter}\"')

        pointsStr = locale.format_string("%d", points, grouping = True)
        multiplierStr = locale.format_string("%d", multiplier, grouping = True)
        prefix = f'{question.getEmote()} CONGRATULATIONS @{userName}, that\'s correct!'
        infix = f'You earned {pointsStr} cuteness ({multiplierStr}x multiplier), so your new cuteness is {newCuteness.getCutenessStr()}.'

        correctAnswers = question.getCorrectAnswers()

        if len(correctAnswers) == 1:
            return f'{prefix} 🎉 {infix} ✨ The correct answer was: {correctAnswers[0]}'
        else:
            correctAnswersStr = delimiter.join(correctAnswers)
            return f'{prefix} 🎉 {infix} ✨ The correct answers were: {correctAnswersStr}'
示例#13
0
async def waitThenSend(
    messageable: Messageable,
    delaySeconds: int,
    message: str,
    heartbeat = lambda: True,
    beforeSend = lambda: None,
    afterSend = lambda: None
):
    if messageable is None:
        raise ValueError(f'messageable argument is malformed: \"{messageable}\"')
    elif not utils.isValidNum(delaySeconds):
        raise ValueError(f'delaySeconds argument is malformed: \"{delaySeconds}\"')
    elif delaySeconds < 1:
        raise ValueError(f'delaySeconds argument is out of bounds: \"{delaySeconds}\"')
    elif not utils.isValidStr(message):
        return
    elif heartbeat is None:
        raise ValueError(f'heartbeat argument is malformed: \"{heartbeat}\"')

    await asyncio.sleep(delaySeconds)

    if heartbeat():
        beforeSend()
        await safeSend(messageable, message)
        afterSend()
示例#14
0
    def getCorrectAnswerReveal(
        self,
        question: AbsTriviaQuestion,
        newCuteness: CutenessResult,
        userNameThatRedeemed: str,
        delimiter: str = '; '
    ) -> str:
        if question is None:
            raise ValueError(f'question argument is malformed: \"{question}\"')
        elif newCuteness is None:
            raise ValueError(f'newCuteness argument is malformed: \"{newCuteness}\"')
        elif not utils.isValidStr(userNameThatRedeemed):
            raise ValueError(f'userNameThatRedeemed argument is malformed: \"{userNameThatRedeemed}\"')
        elif delimiter is None:
            raise ValueError(f'delimiter argument is malformed: \"{delimiter}\"')

        prefix = f'{question.getEmote()} Congratulations @{userNameThatRedeemed}, that\'s correct!'
        infix = f'Your new cuteness is {newCuteness.getCutenessStr()}.'

        correctAnswers = question.getCorrectAnswers()

        if len(correctAnswers) == 1:
            return f'{prefix} 🎉 {infix} ✨ The correct answer was: {correctAnswers[0]}'
        else:
            correctAnswersStr = delimiter.join(correctAnswers)
            return f'{prefix} 🎉 {infix} ✨ The correct answers were: {correctAnswersStr}'
示例#15
0
    async def event_raw_usernotice(self, channel: Channel, tags: Dict):
        if not utils.hasItems(tags):
            return

        msgId = tags.get('msg-id')

        if not utils.isValidStr(msgId):
            return

        twitchUser = await self.__usersRepository.getUserAsync(channel.name)
        generalSettings = await self.__generalSettingsRepository.getAllAsync()

        if msgId == 'raid':
            await self.__raidLogEvent.handleEvent(
                twitchChannel = channel,
                twitchUser = twitchUser,
                tags = tags
            )

            await self.__raidThankEvent.handleEvent(
                twitchChannel = channel,
                twitchUser = twitchUser,
                tags = tags
            )
        elif msgId == 'subgift' or msgId == 'anonsubgift':
            await self.__subGiftThankingEvent.handleEvent(
                twitchChannel = channel,
                twitchUser = twitchUser,
                tags = tags
            )
        elif generalSettings.isDebugLoggingEnabled():
            self.__timber.log('CynanBot', f'event_raw_usernotice(): {tags}')
    def searchPokemon(self, name: str) -> PokepediaPokemon:
        if not utils.isValidStr(name):
            raise ValueError(f'name argument is malformed: \"{name}\"')

        name = utils.cleanStr(name)

        rawResponse = None
        try:
            rawResponse = requests.get(
                url = f'https://pokeapi.co/api/v2/pokemon/{name}/',
                timeout = utils.getDefaultTimeout()
            )
        except (ConnectionError, HTTPError, MaxRetryError, NewConnectionError, Timeout) as e:
            print(f'Exception occurred when attempting to fetch Pokemon \"{name}\": {e}')
            raise RuntimeError(f'Exception occurred when attempting to fetch Pokemon \"{name}\": {e}')

        jsonResponse = None
        try:
            jsonResponse = rawResponse.json()
        except JSONDecodeError as e:
            print(f'Exception occurred when attempting to decode Pokemon response into JSON for \"{name}\": {e}')
            raise RuntimeError(f'Exception occurred when attempting to decode Pokemon response into JSON for \"{name}\": {e}')

        return PokepediaPokemon(
            name = jsonResponse['name'].capitalize()
        )
    def __init__(
        self,
        pokepediaType: PokepediaType,
        name: str,
        rawName: str
    ):
        if pokepediaType is None:
            raise ValueError(f'pokepediaType argument is malformed: \"{pokepediaType}\"')
        elif not utils.isValidStr(name):
            raise ValueError(f'name argument is malformed: \"{name}\"')
        elif not utils.isValidStr(rawName):
            raise ValueError(f'rawName argument is malformed: \"{rawName}\"')

        self.__pokepediaType = pokepediaType
        self.__name = name
        self.__rawName = rawName
示例#18
0
    async def handleEvent(self, twitchChannel: Channel, twitchUser: User,
                          tags: Dict[str, Any]) -> bool:
        if twitchChannel is None:
            raise ValueError(
                f'twitchChannel argument is malformed: \"{twitchChannel}\"')
        elif twitchUser is None:
            raise ValueError(
                f'twitchUser argument is malformed: \"{twitchUser}\"')
        elif tags is None:
            raise ValueError(f'tags argument is malformed: \"{tags}\"')

        generalSettings = await self.__generalSettingsRepository.getAllAsync()
        authSnapshot = await self.__authRepository.getAllAsync()

        if not generalSettings.isSubGiftThankingEnabled():
            return False
        elif not twitchUser.isSubGiftThankingEnabled():
            return False

        giftedByName: str = tags.get('display-name')
        if not utils.isValidStr(giftedByName):
            giftedByName = tags.get('login')

        giftedToName: str = tags.get('msg-param-recipient-display-name')
        if not utils.isValidStr(giftedToName):
            giftedToName = tags.get('msg-param-recipient-user-name')

        if giftedToName.lower() != authSnapshot.requireNick().lower():
            return False
        elif not utils.isValidStr(giftedByName):
            return False
        elif giftedToName.lower() == giftedByName.lower():
            return False

        self.__eventLoop.create_task(
            twitchUtils.waitThenSend(
                messageable=twitchChannel,
                delaySeconds=5,
                message=
                f'😻 Thank you for the gifted sub @{giftedByName}! ✨'))

        self.__timber.log(
            'SubGiftThankingEvent',
            f'{authSnapshot.requireNick()} received sub gift to {twitchUser.getHandle()} from {giftedByName}!'
        )
        return True
    def requireDeepLAuthKey(self) -> str:
        deepLAuthKey = self.getDeepLAuthKey()

        if not utils.isValidStr(deepLAuthKey):
            raise ValueError(
                f'\"deepLAuthKey\" in Auth Repository file (\"{self.__authRepositoryFile}\") is malformed: \"{deepLAuthKey}\"'
            )

        return deepLAuthKey
    def requireTwitchClientId(self) -> str:
        twitchClientId = self.__jsonContents.get('twitchClientId')

        if not utils.isValidStr(twitchClientId):
            raise ValueError(
                f'\"twitchClientId\" in Auth Repository file (\"{self.__authRepositoryFile}\") is malformed: \"{twitchClientId}\"'
            )

        return twitchClientId
    def requireNick(self) -> str:
        nick = self.__jsonContents.get('nick')

        if not utils.isValidStr(nick):
            raise ValueError(
                f'\"nick\" in Auth Repository file (\"{self.__authRepositoryFile}\") is malformed: \"{nick}\"'
            )

        return nick
    def requireOneWeatherApiKey(self) -> str:
        oneWeatherApiKey = self.getOneWeatherApiKey()

        if not utils.isValidStr(oneWeatherApiKey):
            raise ValueError(
                f'\"oneWeatherApiKey\" in Auth Repository file (\"{self.__authRepositoryFile}\") is malformed: \"{oneWeatherApiKey}\"'
            )

        return oneWeatherApiKey
    def __init__(self, definitions: List[str], word: str):
        if not utils.hasItems(definitions):
            raise ValueError(
                f'definitions argument is malformed: \"{definitions}\"')
        elif not utils.isValidStr(word):
            raise ValueError(f'word argument is malformed: \"{word}\"')

        self.__definitions = definitions
        self.__word = word
    def requireTwitchIrcAuthToken(self) -> str:
        twitchIrcAuthToken = self.__jsonContents.get('twitchIrcAuthToken')

        if not utils.isValidStr(twitchIrcAuthToken):
            raise ValueError(
                f'\"twitchIrcAuthToken\" in Auth Repository file (\"{self.__authRepositoryFile}\") is malformed: \"{twitchIrcAuthToken}\"'
            )

        return twitchIrcAuthToken
    def requireMerriamWebsterApiKey(self) -> str:
        merriamWebsterApiKey = self.getMerriamWebsterApiKey()

        if not utils.isValidStr(merriamWebsterApiKey):
            raise ValueError(
                f'\"merriamWebsterApiKey\" in Auth Repository file (\"{self.__authRepositoryFile}\") is malformed: \"{merriamWebsterApiKey}\"'
            )

        return merriamWebsterApiKey
    def requireQuizApiKey(self) -> str:
        quizApiKey = self.getQuizApiKey()

        if not utils.isValidStr(quizApiKey):
            raise ValueError(
                f'\"quizApiKey\" in Auth Repository file (\"{self.__authRepositoryFile}\") is malformed: \"{quizApiKey}\"'
            )

        return quizApiKey
    def getTimeZone(self, timeZone: str):
        if not utils.isValidStr(timeZone):
            return None
        elif timeZone in self.__timeZones:
            return self.__timeZones[timeZone]

        newTimeZone = pytz.timezone(timeZone)
        self.__timeZones[timeZone] = newTimeZone
        return newTimeZone
示例#28
0
    async def handlePointRedemption(self, twitchChannel: Channel,
                                    twitchUser: User, redemptionMessage: str,
                                    rewardId: str, userIdThatRedeemed: str,
                                    userNameThatRedeemed: str) -> bool:
        if twitchChannel is None:
            raise ValueError(
                f'twitchChannel argument is malformed: \"{twitchChannel}\"')
        elif twitchUser is None:
            raise ValueError(
                f'twitchUser argument is malformed: \"{twitchUser}\"')
        elif not utils.isValidStr(rewardId):
            raise ValueError(f'rewardId argument is malformed: \"{rewardId}\"')
        elif not utils.isValidStr(userIdThatRedeemed):
            raise ValueError(
                f'userIdThatRedeemed argument is malformed: \"{userIdThatRedeemed}\"'
            )
        elif not utils.isValidStr(userNameThatRedeemed):
            raise ValueError(
                f'userNameThatRedeemed argument is malformed: \"{userNameThatRedeemed}\"'
            )

        if not twitchUser.isPkmnEnabled():
            return False

        generalSettings = await self.__generalSettingsRepository.getAllAsync()
        actionCompleted = False

        if generalSettings.isFuntoonApiEnabled():
            if await self.__funtoonRepository.pkmnGiveShiny(
                    userThatRedeemed=userNameThatRedeemed,
                    twitchChannel=twitchUser.getHandle()):
                actionCompleted = True

        if not actionCompleted and generalSettings.isFuntoonTwitchChatFallbackEnabled(
        ):
            await twitchUtils.safeSend(twitchChannel,
                                       f'!freeshiny {userNameThatRedeemed}')
            actionCompleted = True

        self.__timber.log(
            'PkmnShinyRedemption',
            f'Redeemed pkmn shiny for {userNameThatRedeemed}:{userIdThatRedeemed} in {twitchUser.getHandle()}'
        )
        return actionCompleted
    def getLanguageForCommand(self, command: str) -> LanguageEntry:
        if not utils.isValidStr(command):
            raise ValueError(f'command argument is malformed: \"{command}\"')

        for entry in self.__entries:
            for commandName in entry.getCommandNames():
                if commandName.lower() == command.lower():
                    return entry

        raise RuntimeError(f'Unable to find language for \"{command}\"')
示例#30
0
    def __init__(self, latitude: float, longitude: float, locationId: str,
                 name: str, timeZone: tzinfo):
        if not utils.isValidNum(latitude):
            raise ValueError(f'latitude argument is malformed: \"{latitude}\"')
        elif not utils.isValidNum(longitude):
            raise ValueError(
                f'longitude argument is malformed: \"{longitude}\"')
        elif not utils.isValidStr(locationId):
            raise ValueError(f'id_ argument is malformed: \"{locationId}\"')
        elif not utils.isValidStr(name):
            raise ValueError(f'name argument is malformed: \"{name}\"')
        elif timeZone is None:
            raise ValueError(f'timeZone argument is malformed: \"{timeZone}\"')

        self.__latitude = latitude
        self.__longitude = longitude
        self.__locationId = locationId
        self.__name = name
        self.__timeZone = timeZone