コード例 #1
0
ファイル: events.py プロジェクト: charlesmadere/CynanBot
    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
コード例 #2
0
    def getRefreshPubSubTokensSeconds(self) -> int:
        refreshPubSubTokensSeconds = utils.getIntFromDict(
            self.__jsonContents, 'refreshPubSubTokensSeconds', 120)

        if refreshPubSubTokensSeconds < 30:
            raise ValueError(
                f'\"refreshPubSubTokensSeconds\" value in General Settings file (\"{self.__generalSettingsFile}\") is too aggressive: {refreshPubSubTokensSeconds}'
            )

        return refreshPubSubTokensSeconds
コード例 #3
0
ファイル: events.py プロジェクト: charlesmadere/CynanBot
    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
コード例 #4
0
    def __fetchAirQuality(self, location: Location) -> int:
        if location is None:
            raise ValueError(f'location argument is malformed: \"{location}\"')

        # Retrieve air quality from: https://api-docs.iqair.com/
        # Doing this requires an API key, which you can get here:
        # https://www.iqair.com/us/commercial/air-quality-monitors/airvisual-platform/api

        requestUrl = 'https://api.airvisual.com/v2/nearest_city?key={}&lat={}&lon={}'.format(
            self.__iqAirApiKey, location.getLatitude(),
            location.getLongitude())

        rawResponse = None
        try:
            rawResponse = requests.get(url=requestUrl,
                                       timeout=utils.getDefaultTimeout())
        except (ConnectionError, HTTPError, MaxRetryError, NewConnectionError,
                Timeout) as e:
            print(
                f'Exception occurred when attempting to fetch air quality from IQAir for \"{location.getLocationId()}\": {e}'
            )
            raise RuntimeError(
                f'Exception occurred when attempting to fetch air quality from IQAir for \"{location.getLocationId()}\": {e}'
            )

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

        if jsonResponse.get('status') != 'success':
            print(
                f'IQAir\'s response \"status\" was not \"success\": {jsonResponse}'
            )
            raise ValueError(
                f'IQAir\'s response \"status\" was not \"success\": {jsonResponse}'
            )

        return utils.getIntFromDict(
            d=jsonResponse['data']['current']['pollution'], key='aqius')
コード例 #5
0
    def __parseCutenessBoosterPacksFromJson(
            self, jsonList: List[Dict]) -> List[CutenessBoosterPack]:
        if not utils.hasItems(jsonList):
            return None

        cutenessBoosterPacks: List[CutenessBoosterPack] = list()

        for cutenessBoosterPackJson in jsonList:
            cutenessBoosterPacks.append(
                CutenessBoosterPack(
                    amount=utils.getIntFromDict(cutenessBoosterPackJson,
                                                'amount'),
                    rewardId=utils.getStrFromDict(cutenessBoosterPackJson,
                                                  'rewardId')))

        cutenessBoosterPacks.sort(key=lambda pack: pack.getAmount())
        return cutenessBoosterPacks
コード例 #6
0
 def getWaitForTriviaAnswerDelay(self) -> int:
     return utils.getIntFromDict(self.__jsonContents,
                                 'waitForTriviaAnswerDelay', 45)
コード例 #7
0
 def getTriviaGameTutorialCutenessThreshold(self) -> int:
     return utils.getIntFromDict(self.__jsonContents,
                                 'triviaGameTutorialCutenessThreshold', 10)
コード例 #8
0
 def getTriviaGamePoints(self) -> int:
     return utils.getIntFromDict(self.__jsonContents, 'triviaGamePoints', 5)
コード例 #9
0
 def getSuperTriviaGamePerUserAttempts(self) -> int:
     return utils.getIntFromDict(self.__jsonContents,
                                 'superTriviaGamePerUserAttempts', 2)
コード例 #10
0
 def getSuperTriviaGameMultiplier(self) -> int:
     return utils.getIntFromDict(self.__jsonContents,
                                 'superTriviaGameMultiplier', 5)
コード例 #11
0
 def getRaidLinkMessagingDelay(self) -> int:
     return utils.getIntFromDict(self.__jsonContents,
                                 'raidLinkMessagingDelay', 60)
コード例 #12
0
 def getEventSubPort(self) -> int:
     return utils.getIntFromDict(self.__jsonContents, 'eventSubPort', 33239)