class TwitchEmoteManager(GenericChannelEmoteManager): redis_name = "twitch" friendly_name = "Twitch" def __init__(self, client_id): from pajbot.apiwrappers import TwitchAPI self.api = TwitchAPI(client_id) self.tier_one_emotes = [] self.tier_two_emotes = [] self.tier_three_emotes = [] super().__init__() @property def channel_emotes(self): return self.tier_one_emotes def update_channel_emotes(self): streamer = StreamHelper.get_streamer() self.tier_one_emotes, self.tier_two_emotes, self.tier_three_emotes = self.api.get_channel_emotes(streamer) self.save_cached_subemotes( self.channel_emote_redis_key, self.tier_one_emotes, self.tier_two_emotes, self.tier_three_emotes ) log.info("Successfully updated {} channel emotes".format(self.friendly_name)) def load_channel_emotes(self): """Load channel emotes from the cache if available, or else, query the API.""" self.tier_one_emotes, self.tier_two_emotes, self.tier_three_emotes = self.load_cached_subemotes( self.channel_emote_redis_key ) # no channel emotes in cache? load from API and save to cache. if self.tier_one_emotes is None or self.tier_two_emotes is None or self.tier_three_emotes is None: self.update_channel_emotes() @staticmethod def load_cached_subemotes(redis_key): try: redis = RedisManager.get() redis_result = redis.get(redis_key) if redis_result is None: return None, None, None obj = {key: [Emote(**args) for args in value] for key, value in json.loads(redis_result).items()} return obj["1"], obj["2"], obj["3"] except: log.exception("Failed to get subemotes from key {} from redis".format(redis_key)) return [], [], [] @staticmethod def save_cached_subemotes(redis_key, tier_one, tier_two, tier_three): try: redis = RedisManager.get() # emotes expire after 1 hour dict = {"1": tier_one, "2": tier_two, "3": tier_three} dict = {key: [emote.jsonify() for emote in emotes] for key, emotes in dict.items()} redis.setex(redis_key, 60 * 60, json.dumps(dict)) except: log.exception("Error saving subemotes to redis key {}".format(redis_key))