def update_emotes(self): log.debug('Updating BTTV Emotes...') global_emotes = self.bttv_api.get_global_emotes() channel_emotes = self.bttv_api.get_channel_emotes(StreamHelper.get_streamer()) self.global_emotes = [emote['code'] for emote in global_emotes] self.channel_emotes = [emote['code'] for emote in channel_emotes] # Store channel emotes in redis streamer = StreamHelper.get_streamer() key = '{streamer}:emotes:bttv_channel_emotes'.format(streamer=streamer) with RedisManager.pipeline_context() as pipeline: pipeline.delete(key) for emote in channel_emotes: pipeline.hset(key, emote['code'], emote['emote_hash']) self.all_emotes = [] with RedisManager.pipeline_context() as pipeline: for emote in global_emotes + channel_emotes: # Store all possible emotes, with their regex in an easily # accessible list. self.all_emotes.append(self.build_emote(emote['code'], emote['emote_hash'])) # Make sure all available emotes are available in redis pipeline.hset('global:emotes:bttv', emote['code'], emote['emote_hash'])
def username_raw(self, value): # Set cached value self.values['username_raw'] = value # Set redis value if value != self.username: self.redis.hset('{streamer}:users:username_raw'.format(streamer=StreamHelper.get_streamer()), self.username, value) else: self.redis.hdel('{streamer}:users:username_raw'.format(streamer=StreamHelper.get_streamer()), self.username)
def banned(self, value): # Set cached value self.values['banned'] = value if value is True: # Set redis value self.redis.hset('{streamer}:users:banned'.format(streamer=StreamHelper.get_streamer()), self.username, 1) else: self.redis.hdel('{streamer}:users:banned'.format(streamer=StreamHelper.get_streamer()), self.username)
def tokens(self, value): # Set cached value self.values['tokens'] = value if self.save_to_redis: # Set redis value if value != 0: self.redis.zadd('{streamer}:users:tokens'.format(streamer=StreamHelper.get_streamer()), self.username, value) else: self.redis.zrem('{streamer}:users:tokens'.format(streamer=StreamHelper.get_streamer()), self.username)
def update_channel_emotes(self): _channel_emotes = self.api.get_channel_emotes(StreamHelper.get_streamer()) self.channel_emotes = {} for emote in _channel_emotes: self.channel_emotes[emote['code']] = emote['emote_hash'] # Store channel emotes in redis streamer = StreamHelper.get_streamer() key = '{streamer}:emotes:bttv_channel_emotes'.format(streamer=streamer) with RedisManager.pipeline_context() as pipeline: pipeline.delete(key) for emote_code, emote_hash in self.channel_emotes.items(): pipeline.hset(key, emote_code, emote_hash)
def stats(): bot_commands_list = pajbot.web.utils.get_cached_commands() top_5_commands = sorted(bot_commands_list, key=lambda c: c['data']['num_uses'] if c['data'] is not None else -1, reverse=True)[:5] redis = RedisManager.get() # TODO: Make this hideable through some magic setting (NOT config.ini @_@) with DBManager.create_session_scope() as db_session: top_5_line_farmers = [] for redis_user in redis.zrevrangebyscore( '{streamer}:users:num_lines'.format(streamer=StreamHelper.get_streamer()), '+inf', '-inf', start=0, num=5, withscores=True, score_cast_func=int): user = UserManager.get_static(redis_user[0], db_session=db_session) user.save_to_redis = False user.num_lines = redis_user[1] top_5_line_farmers.append(user) data = { 'top_5_winners': db_session.query(UserDuelStats).order_by(UserDuelStats.duels_won.desc())[:5], 'top_5_points_won': db_session.query(UserDuelStats).order_by(UserDuelStats.profit.desc())[:5], 'top_5_points_lost': db_session.query(UserDuelStats).order_by(UserDuelStats.profit.asc())[:5], 'top_5_losers': db_session.query(UserDuelStats).order_by(UserDuelStats.duels_lost.desc())[:5], 'top_5_winrate': db_session.query(UserDuelStats).filter(UserDuelStats.duels_won >= 5).order_by(UserDuelStats.winrate.desc())[:5], 'bottom_5_winrate': db_session.query(UserDuelStats).filter(UserDuelStats.duels_lost >= 5).order_by(UserDuelStats.winrate.asc())[:5], } return render_template('stats.html', **data, top_5_commands=top_5_commands, top_5_line_farmers=top_5_line_farmers)
def num_lines_rank(self): key = "{streamer}:users:num_lines".format(streamer=StreamHelper.get_streamer()) rank = self.redis.zrevrank(key, self.username) if rank is None: return self.redis.zcard(key) return rank + 1
def set_last_seen(self, value): # Set cached value value = value.timestamp() self.values["last_seen"] = value # Set redis value self.redis.hset("{streamer}:users:last_seen".format(streamer=StreamHelper.get_streamer()), self.username, value)
def stats(): bot_commands_list = pajbot.web.utils.get_cached_commands() top_5_commands = sorted(bot_commands_list, key=lambda c: c["data"]["num_uses"] if c["data"] is not None else -1, reverse=True)[:5] redis = RedisManager.get() # TODO: Make this hideable through some magic setting (NOT config.ini @_@) with DBManager.create_session_scope() as db_session: top_5_line_farmers = [] for redis_user in redis.zrevrangebyscore( "{streamer}:users:num_lines".format( streamer=StreamHelper.get_streamer()), "+inf", "-inf", start=0, num=5, withscores=True, score_cast_func=int, ): user = UserManager.get_static(redis_user[0], db_session=db_session) user.save_to_redis = False top_5_line_farmers.append(user) return render_template("stats.html", top_5_commands=top_5_commands, top_5_line_farmers=top_5_line_farmers)
def delete(self, **options): # Add a single tag to the email args = self.delete_parser.parse_args() email = args['email'].lower() new_tag = args['tag'].lower() streamer = StreamHelper.get_streamer() key = '{streamer}:email_tags'.format(streamer=streamer) redis = RedisManager.get() tags_str = redis.hget(key, email) if tags_str is None: tags = [] else: tags = json.loads(tags_str) # Is the tag already active? if new_tag not in tags: return { 'message': 'This tag is not set on the email.' }, 409 tags.remove(new_tag) if len(tags) > 0: redis.hset(key, email, json.dumps(tags)) else: redis.hdel(key, email) return { 'message': 'Successfully removed the tag {} from {}'.format(new_tag, email) }
def load_commands(self, **options): self.commands["clip"] = Command.raw_command( self.clip, sub_only=self.settings["subscribers_only"], delay_all=self.settings["global_cd"], delay_user=self.settings["user_cd"], level=self.settings["level"], can_execute_with_whisper=bool( self.settings["response_method"] == "reply"), command="clip", examples=[ CommandExample( None, "Make a new clip while the stream is online", chat="user:!clip\n" "bot: " + self.settings["online_response"].format( source="pajlada", streamer=StreamHelper.get_streamer(), clip= "https://clips.twitch.tv/ExpensiveWonderfulClamArsonNoSexy", ), description="", ).parse() ], )
def award_tokens(self, tokens, redis=None, force=False): """ Returns True if tokens were awarded properly. Returns False if not. Tokens can only be rewarded once per stream ID. """ streamer = StreamHelper.get_streamer() stream_id = StreamHelper.get_current_stream_id() if stream_id is False: return False if redis is None: redis = RedisManager.get() key = '{streamer}:{username}:tokens'.format( streamer=streamer, username=self.username) if force: res = True redis.hset(key, stream_id, tokens) else: res = True if redis.hsetnx(key, stream_id, tokens) == 1 else False if res is True: HandlerManager.trigger('on_user_gain_tokens', self, tokens) return res
def progress_quest(self, amount, limit, completion_reward): """ Progress the quest for `stream_id` by `amount`. We load data from redis in case no progress has been made yet. """ streamer = StreamHelper.get_streamer() stream_id = StreamHelper.get_current_stream_id() if stream_id is False: return False redis = RedisManager.get() quest_progress_key = '{streamer}:{stream_id}:{username}:quest_progress'.format( streamer=streamer, stream_id=stream_id, username=self.username) if stream_id not in self.quest_progress: # Load the old progress, or set it to 0 if no progress was found self.init_quest_progress() if self.quest_progress[stream_id] >= limit: # The user has already completed this quest. return False self.quest_progress[stream_id] += amount if self.quest_progress[stream_id] >= limit: # The user just completed the quest for the first time self.award_tokens(completion_reward, redis=redis) return False redis.set(quest_progress_key, self.quest_progress[stream_id])
def tokens(self, value): # Set cached value self.values["tokens"] = value if self.save_to_redis: # Set redis value if value != 0: self.redis.zadd( "{streamer}:users:tokens".format( streamer=StreamHelper.get_streamer()), {self.username: float(value)}, ) else: self.redis.zrem( "{streamer}:users:tokens".format( streamer=StreamHelper.get_streamer()), self.username)
def spend_tokens(self, tokens_to_spend, redis=None): if redis is None: redis = RedisManager.get() user_token_key = '{streamer}:{username}:tokens'.format( streamer=StreamHelper.get_streamer(), username=self.username) token_dict = redis.hgetall(user_token_key) for stream_id in token_dict: try: num_tokens = int(token_dict[stream_id]) except (TypeError, ValueError): continue if num_tokens == 0: continue decrease_by = min(tokens_to_spend, num_tokens) tokens_to_spend -= decrease_by num_tokens -= decrease_by redis.hset(user_token_key, stream_id, num_tokens) if tokens_to_spend == 0: return True return False
def delete(self, **options): # Add a single tag to the email args = self.delete_parser.parse_args() email = args['email'].lower() new_tag = args['tag'].lower() streamer = StreamHelper.get_streamer() key = '{streamer}:email_tags'.format(streamer=streamer) redis = RedisManager.get() tags_str = redis.hget(key, email) if tags_str is None: tags = [] else: tags = json.loads(tags_str) # Is the tag already active? if new_tag not in tags: return {'message': 'This tag is not set on the email.'}, 409 tags.remove(new_tag) if len(tags) > 0: redis.hset(key, email, json.dumps(tags)) else: redis.hdel(key, email) return { 'message': 'Successfully removed the tag {} from {}'.format( new_tag, email) }
def incr_num_lines(self): # Set cached value self.values['num_lines'] = self.num_lines + 1 if self.save_to_redis: # Set redis value self.redis.zincrby('{streamer}:users:num_lines'.format(streamer=StreamHelper.get_streamer()), value=self.username, amount=1.0)
def test(): redis = RedisManager.get() current_quest_key = '{streamer}:current_quest'.format(streamer=StreamHelper.get_streamer()) current_quest_id = redis.get(current_quest_key) current_quest = module_manager[current_quest_id] current_quest.load_data() return render_template('test.html', current_quest=current_quest)
def award_tokens(self, tokens, redis=None, force=False): """ Returns True if tokens were awarded properly. Returns False if not. Tokens can only be rewarded once per stream ID. """ streamer = StreamHelper.get_streamer() stream_id = StreamHelper.get_current_stream_id() if stream_id is False: return False if redis is None: redis = RedisManager.get() key = '{streamer}:{username}:tokens'.format(streamer=streamer, username=self.username) if force: res = True redis.hset(key, stream_id, tokens) else: res = True if redis.hsetnx(key, stream_id, tokens) == 1 else False if res is True: HandlerManager.trigger('on_user_gain_tokens', self, tokens) return res
def load_commands(self, **options): # TODO: Aliases should be set in settings? # This way, it can be run alongside other modules self.commands["song"] = Command.raw_command( self.song, delay_all=self.settings["global_cd"], delay_user=self.settings["user_cd"], description="Check what that is playing on the stream", examples=[ CommandExample( None, "Check the current song", chat="user:!song\n" "bot: " + self.settings["current_song"].format( source="pajlada", streamer=StreamHelper.get_streamer(), song="Adele - Hello", ), description= "Bot mentions the name of the song and the artist currently playing on stream", ).parse() ], ) self.commands["currentsong"] = self.commands["song"] self.commands["nowplaying"] = self.commands["song"] self.commands["playing"] = self.commands["song"]
def on_stream_stop(self): if self.current_quest is None: log.info('No quest active on stream stop.') return False self.current_quest.stop_quest() self.current_quest = None self.bot.say('Stream ended, quest has been reset.') redis = RedisManager.get() # Remove any mentions of the current quest redis.delete(self.current_quest_key) last_stream_id = StreamHelper.get_last_stream_id() if last_stream_id is False: log.error('No last stream ID found.') # No last stream ID found. why? return False # XXX: Should we use a pipeline for any of this? # Go through user tokens and remove any from more than 2 streams ago for key in redis.keys('{streamer}:*:tokens'.format(streamer=StreamHelper.get_streamer())): all_tokens = redis.hgetall(key) for stream_id_str in all_tokens: try: stream_id = int(stream_id_str) except (TypeError, ValueError): log.error('Invalid stream id in tokens by {}'.format(key)) continue if last_stream_id - stream_id > 1: log.info('Removing tokens for stream {}'.format(stream_id)) redis.hdel(key, stream_id)
def get_emote_count(emote_code): redis = RedisManager.get() streamer = StreamHelper.get_streamer() emote_count = redis.zscore(f"{streamer}:emotes:count", emote_code) if emote_count is None: return None return int(emote_count)
def progress_quest(self, amount, limit, completion_reward): """ Progress the quest for `stream_id` by `amount`. We load data from redis in case no progress has been made yet. """ streamer = StreamHelper.get_streamer() stream_id = StreamHelper.get_current_stream_id() if stream_id is False: return False redis = RedisManager.get() quest_progress_key = '{streamer}:{stream_id}:{username}:quest_progress'.format( streamer=streamer, stream_id=stream_id, username=self.username) if stream_id not in self.quest_progress: # Load the old progress, or set it to 0 if no progress was found self.init_quest_progress() if self.quest_progress[stream_id] >= limit: # The user has already completed this quest. return False self.quest_progress[stream_id] += amount if self.quest_progress[stream_id] >= limit: # The user just completed the quest for the first time self.award_tokens(completion_reward, redis=redis) return False redis.set(quest_progress_key, self.quest_progress[stream_id])
def __init__(self): from pajbot.apiwrappers.bttv import BTTVAPI self.api = BTTVAPI(RedisManager.get()) self.streamer = StreamHelper.get_streamer() self.streamer_id = StreamHelper.get_streamer_id() super().__init__()
def spend_tokens(self, tokens_to_spend, redis=None): if redis is None: redis = RedisManager.get() user_token_key = '{streamer}:{username}:tokens'.format( streamer=StreamHelper.get_streamer(), username=self.username) token_dict = redis.hgetall(user_token_key) for stream_id in token_dict: try: num_tokens = int(token_dict[stream_id]) except (TypeError, ValueError): continue if num_tokens == 0: continue decrease_by = min(tokens_to_spend, num_tokens) tokens_to_spend -= decrease_by num_tokens -= decrease_by redis.hset(user_token_key, stream_id, num_tokens) if tokens_to_spend == 0: return True return False
def __init__(self): self._global_emotes = [] self._channel_emotes = [] self.streamer = StreamHelper.get_streamer() self.streamer_id = StreamHelper.get_streamer_id() self.global_lookup_table = {} self.channel_lookup_table = {}
def handle_emotes(emote_counts): # passed dict maps emote code (e.g. "Kappa") to an EmoteInstanceCount instance streamer = StreamHelper.get_streamer() redis_key = "{streamer}:emotes:count".format(streamer=streamer) with RedisManager.pipeline_context() as redis: for emote_code, instance_counts in emote_counts.items(): redis.zincrby(redis_key, instance_counts.count, emote_code)
def stats(): bot_commands_list = pajbot.web.utils.get_cached_commands() top_5_commands = sorted(bot_commands_list, key=lambda c: c['data']['num_uses'] if c['data'] is not None else -1, reverse=True)[:5] redis = RedisManager.get() # TODO: Make this hideable through some magic setting (NOT config.ini @_@) with DBManager.create_session_scope() as db_session: top_5_line_farmers = [] for redis_user in redis.zrevrangebyscore( '{streamer}:users:num_lines'.format(streamer=StreamHelper.get_streamer()), '+inf', '-inf', start=0, num=5, withscores=True, score_cast_func=int): user = UserManager.get_static(redis_user[0], db_session=db_session) user.save_to_redis = False user.num_lines = redis_user[1] top_5_line_farmers.append(user) return render_template('stats.html', top_5_commands=top_5_commands, top_5_line_farmers=top_5_line_farmers)
def update_channel_emotes(self): streamer = StreamHelper.get_streamer() self.channel_emotes = self.api.get_channel_emotes(streamer) self.save_cached_emotes(self.channel_emote_redis_key, self.channel_emotes) log.info("Successfully updated {} channel emotes".format( self.friendly_name))
def _set_last_seen(self, value): # Set cached value self.values['last_seen'] = value self.redis.hset( '{streamer}:users:last_seen'.format( streamer=StreamHelper.get_streamer()), self.username, value)
def num_lines_rank(self): key = '{streamer}:users:num_lines'.format(streamer=StreamHelper.get_streamer()) rank = self.redis.zrevrank(key, self.username) if rank is None: return self.redis.zcard(key) else: return rank + 1
def post(self, **options): # Add a single tag to the email args = self.post_parser.parse_args() email = args["email"].lower() new_tag = args["tag"].lower() if len(new_tag) == 0: return {"message": "The tag must be at least 1 character long."}, 400 streamer = StreamHelper.get_streamer() key = "{streamer}:email_tags".format(streamer=streamer) redis = RedisManager.get() tags_str = redis.hget(key, email) if tags_str is None: tags = [] else: tags = json.loads(tags_str) # Is the tag already active? if new_tag in tags: return {"message": "This tag is already set on the email."}, 409 tags.append(new_tag) redis.hset(key, email, json.dumps(tags)) return {"message": "Successfully added the tag {} to {}".format(new_tag, email)}
def _last_active(self, value): # Set cached value value = value.timestamp() self.values['last_active'] = value # Set redis value self.redis.hset('{streamer}:users:last_active'.format(streamer=StreamHelper.get_streamer()), self.username, value)
def post(self, **options): # Add a single tag to the email args = self.post_parser.parse_args() email = args['email'].lower() new_tag = args['tag'].lower() if len(new_tag) == 0: return { 'message': 'The tag must be at least 1 character long.' }, 400 streamer = StreamHelper.get_streamer() key = '{streamer}:email_tags'.format(streamer=streamer) redis = RedisManager.get() tags_str = redis.hget(key, email) if tags_str is None: tags = [] else: tags = json.loads(tags_str) # Is the tag already active? if new_tag in tags: return { 'message': 'This tag is already set on the email.' }, 409 tags.append(new_tag) redis.hset(key, email, json.dumps(tags)) return { 'message': 'Successfully added the tag {} to {}'.format(new_tag, email) }
def on_stream_stop(self): if self.current_quest is None: log.info('No quest active on stream stop.') return False self.current_quest.stop_quest() self.current_quest = None self.bot.say('Stream ended, quest has been reset.') redis = RedisManager.get() # Remove any mentions of the current quest redis.delete(self.current_quest_key) last_stream_id = StreamHelper.get_last_stream_id() if last_stream_id is False: log.error('No last stream ID found.') # No last stream ID found. why? return False # XXX: Should we use a pipeline for any of this? # Go through user tokens and remove any from more than 2 streams ago for key in redis.keys('{streamer}:*:tokens'.format(streamer=StreamHelper.get_streamer())): all_tokens = redis.hgetall(key) for stream_id_str in all_tokens: try: stream_id = int(stream_id_str) except (TypeError, ValueError): log.error('Invalid stream id in tokens by {}'.format(key)) continue if last_stream_id - stream_id > 1: log.info('Removing tokens for stream {}'.format(stream_id)) redis.hdel(key, stream_id)
def donations(widget_id, **options): redis = RedisManager.get() widget = redis.hget( '{streamer}:clr:donations'.format( streamer=StreamHelper.get_streamer()), widget_id) if widget is None: abort(404) widget = json.loads(widget) # Assign indices to all styles and conditions i = 0 log.info(widget['styles']) for style in widget['styles']: style['index'] = i i += 1 log.info(widget['styles']) i = 0 j = 0 for condition in widget['conditions']: condition['index'] = i i += 1 for style in condition['styles']: style['index'] = j j += 1 log.info(widget) operator_order = { '==': 100, '>=': 50, '<=': 50, } widget['conditions'].sort( key=lambda c: (operator_order[c['operator']], c['amount'])) tts_authentication = '' if 'extra' in config: tts_authentication = config['extra'].get('tts_authentication', '') redis = RedisManager.get() twitch_emotes = redis.hgetall('global:emotes:twitch') bttv_emotes = redis.hgetall('global:emotes:bttv') emotes = [] for emote in twitch_emotes: emotes.append({ 'code': emote, 'emote_id': twitch_emotes[emote], }) for emote in bttv_emotes: emotes.append({ 'code': emote, 'emote_hash': bttv_emotes[emote], }) emotes.sort(key=lambda emote: len(emote['code']), reverse=True) return render_template('clr/donations.html', widget=widget, emotes=emotes, tts_authentication=tts_authentication)
def __init__(self): from pajbot.apiwrappers import BTTVApi self.bttv_api = BTTVApi() self.global_emotes = [] streamer = StreamHelper.get_streamer() redis = RedisManager.get() self.channel_emotes = redis.lrange('{streamer}:emotes:bttv_channel_emotes'.format(streamer=streamer), 0, -1) self.all_emotes = []
def get_emote_epmrecord(self, emote_code): redis = RedisManager.get() streamer = StreamHelper.get_streamer() emote_count = redis.zscore('{streamer}:emotes:epmrecord'.format(streamer=streamer), emote_code) if emote_count: return int(emote_count) return None
def donations(widget_id, **options): redis = RedisManager.get() widget = redis.hget( '{streamer}:clr:donations'.format(streamer=StreamHelper.get_streamer()), widget_id) if widget is None: abort(404) widget = json.loads(widget) # Assign indices to all styles and conditions i = 0 log.info(widget['styles']) for style in widget['styles']: style['index'] = i i += 1 log.info(widget['styles']) i = 0 j = 0 for condition in widget['conditions']: condition['index'] = i i += 1 for style in condition['styles']: style['index'] = j j += 1 log.info(widget) operator_order = { '==': 100, '>=': 50, '<=': 50, } widget['conditions'].sort(key=lambda c: (operator_order[c['operator']], c['amount'])) tts_authentication = '' if 'extra' in config: tts_authentication = config['extra'].get('tts_authentication', '') redis = RedisManager.get() twitch_emotes = redis.hgetall('global:emotes:twitch') bttv_emotes = redis.hgetall('global:emotes:bttv') emotes = [] for emote in twitch_emotes: emotes.append({ 'code': emote, 'emote_id': twitch_emotes[emote], }) for emote in bttv_emotes: emotes.append({ 'code': emote, 'emote_hash': bttv_emotes[emote], }) emotes.sort(key=lambda emote: len(emote['code']), reverse=True) return render_template('clr/donations.html', widget=widget, emotes=emotes, tts_authentication=tts_authentication)
def queue_up_redis_calls(self, pipeline): streamer = StreamHelper.get_streamer() # Queue up calls to the pipeline for key in UserRedis.SS_KEYS: pipeline.zscore("{streamer}:users:{key}".format(streamer=streamer, key=key), self.username) for key in UserRedis.HASH_KEYS: pipeline.hget("{streamer}:users:{key}".format(streamer=streamer, key=key), self.username) for key in UserRedis.BOOL_KEYS: pipeline.hget("{streamer}:users:{key}".format(streamer=streamer, key=key), self.username)
def queue_up_redis_calls(self, pipeline): streamer = StreamHelper.get_streamer() # Queue up calls to the pipeline for key in UserRedis.SS_KEYS: pipeline.zscore('{streamer}:users:{key}'.format(streamer=streamer, key=key), self.username) for key in UserRedis.HASH_KEYS: pipeline.hget('{streamer}:users:{key}'.format(streamer=streamer, key=key), self.username) for key in UserRedis.BOOL_KEYS: pipeline.hget('{streamer}:users:{key}'.format(streamer=streamer, key=key), self.username)
def get_emote_count(self, emote_code): redis = RedisManager.get() streamer = StreamHelper.get_streamer() emote_count = redis.zscore( '{streamer}:emotes:count'.format(streamer=streamer), emote_code) if emote_count: return int(emote_count) return None
def __init__(self, twitch_helix_api): self.twitch_helix_api = twitch_helix_api self.streamer = StreamHelper.get_streamer() self.streamer_id = StreamHelper.get_streamer_id() self.tier_one_emotes = [] self.tier_two_emotes = [] self.tier_three_emotes = [] super().__init__()
def __init__(self, twitch_helix_api: TwitchHelixAPI) -> None: self.twitch_helix_api = twitch_helix_api self.streamer = StreamHelper.get_streamer() self.streamer_id = StreamHelper.get_streamer_id() self.tier_one_emotes: List[Emote] = [] self.tier_two_emotes: List[Emote] = [] self.tier_three_emotes: List[Emote] = [] super().__init__(None)
def __init__(self, bot): super().__init__(bot) self.points_required_key = "{streamer}:current_quest_points_required".format( streamer=StreamHelper.get_streamer() ) # The points_required variable is randomized at the start of the quest. # It will be a value between settings['min_value'] and settings['max_value'] self.points_required = None self.progress = {}
def __init__(self): super().__init__() # XXX: This key should probably be generic and always set in the BaseQuest self.points_required_key = '{streamer}:current_quest_points_required'.format( streamer=StreamHelper.get_streamer()) # The points_required variable is randomized at the start of the quest. # It will be a value between settings['min_value'] and settings['max_value'] self.points_required = None self.progress = {}
def __init__(self, api: Optional[EmoteAPI]) -> None: self._global_emotes: List[Emote] = [] self._channel_emotes: List[Emote] = [] self.streamer = StreamHelper.get_streamer() self.streamer_id = StreamHelper.get_streamer_id() self.global_lookup_table: Dict[str, Emote] = {} self.channel_lookup_table: Dict[str, Emote] = {} self.api = api
def index(): custom_content = custom_web_content.get('home', '') try: custom_content = Markup(markdown.markdown(custom_content)) except: log.exception('Unhandled exception in def index') redis = RedisManager.get() streamer = StreamHelper.get_streamer() keys = ('online', 'viewers', 'game') stream_data_keys = ['{streamer}:{key}'.format(streamer=streamer, key=key) for key in keys] stream_data_list = redis.hmget('stream_data', stream_data_keys) stream_data = {keys[x]: stream_data_list[x] for x in range(0, len(keys))} keys = StreamHelper.social_keys streamer_info_keys = ['{streamer}:{key}'.format(streamer=streamer, key=key) for key in keys.keys()] log.info(streamer_info_keys) streamer_info_list = redis.hmget('streamer_info', streamer_info_keys) streamer_info = collections.OrderedDict() for key in keys: value = streamer_info_list.pop(0) if value: streamer_info[key] = { 'value': keys[key]['format'].format(value), 'title': keys[key]['title'], 'format': keys[key]['format'], } current_quest_key = '{streamer}:current_quest'.format(streamer=StreamHelper.get_streamer()) current_quest_id = redis.get(current_quest_key) if current_quest_id is not None: current_quest = module_manager[current_quest_id] if current_quest: current_quest.load_data() else: current_quest = None return render_template('index.html', custom_content=custom_content, current_quest=current_quest, stream_data=stream_data, streamer_info=streamer_info)
def __init__(self, twitch_v5_api): self.api = TwitchEmotesAPI(RedisManager.get()) self.twitch_v5_api = twitch_v5_api self.streamer = StreamHelper.get_streamer() self.streamer_id = StreamHelper.get_streamer_id() self.tier_one_emotes = [] self.tier_two_emotes = [] self.tier_three_emotes = [] super().__init__()
def __init__(self): from pajbot.apiwrappers import BTTVApi self.bttv_api = BTTVApi() self.global_emotes = [] streamer = StreamHelper.get_streamer() redis = RedisManager.get() self.channel_emotes = redis.lrange( '{streamer}:emotes:bttv_channel_emotes'.format(streamer=streamer), 0, -1) self.all_emotes = []
def __init__(self): super().__init__() # XXX: This key should probably be generic and always set in the BaseQuest self.points_required_key = "{streamer}:current_quest_points_required".format( streamer=StreamHelper.get_streamer() ) # The points_required variable is randomized at the start of the quest. # It will be a value between settings['min_value'] and settings['max_value'] self.points_required = None self.progress = {}
def load_cached_channel_emotes(self): streamer = StreamHelper.get_streamer() # Try to get the list of global emotes from redis try: _channel_emotes = RedisManager.get().hgetall('{streamer}:emotes:bttv_channel_emotes'.format(streamer=streamer)) except: _channel_emotes = {} for code in _channel_emotes: emote_hash = _channel_emotes[code] self.channel_emotes[code] = emote_hash
def post(self, widget_id, **options): args = self.post_parser.parse_args() # special case for boolean values args['tts'] = args['tts'] == 'true' streamer = StreamHelper.get_streamer() key = '{streamer}:clr:donations'.format(streamer=streamer) redis = RedisManager.get() redis.hset(key, widget_id, json.dumps(args)) return { 'message': 'GOT EM' }, 200
def clr_donations_home(**options): redis = RedisManager.get() key = '{streamer}:clr:donations'.format(streamer=StreamHelper.get_streamer()) widgets = redis.hgetall(key) # Make sure all the widget data is converted from a string to a dictionary for widget_id in widgets: widgets[widget_id] = json.loads(widgets[widget_id]) new_widget_id = None while new_widget_id is None or new_widget_id in widgets: new_widget_id = binascii.hexlify(os.urandom(32)).decode('utf8').upper() return render_template('admin/clr/donations/home.html', widgets=widgets, new_widget_id=new_widget_id)
def clr_donations_edit(widget_id, **options): redis = RedisManager.get() widget = redis.hget( '{streamer}:clr:donations'.format(streamer=StreamHelper.get_streamer()), widget_id) new = False if widget is None: widget = {} new = True else: widget = json.loads(widget) return render_template('admin/clr/donations/edit.html', widget_id=widget_id, widget_data=json.dumps(widget), new=new)
def get_tokens(self, redis=None): streamer = StreamHelper.get_streamer() if redis is None: redis = RedisManager.get() tokens = redis.hgetall('{streamer}:{username}:tokens'.format( streamer=streamer, username=self.username)) num_tokens = 0 for token_value in tokens.values(): try: num_tokens += int(token_value) except (TypeError, ValueError): log.warn('Invalid value for tokens, user {}'.format(self.username)) return num_tokens
def admin_streamer(**options): redis = RedisManager.get() streamer = StreamHelper.get_streamer() keys = StreamHelper.social_keys streamer_info_keys = ['{streamer}:{key}'.format(streamer=streamer, key=key) for key in keys.keys()] log.info(streamer_info_keys) streamer_info_list = redis.hmget('streamer_info', streamer_info_keys) streamer_info = collections.OrderedDict() for key in keys: value = streamer_info_list.pop(0) streamer_info[key] = { 'value': value, 'title': keys[key]['title'], 'format': keys[key]['format'], } return render_template('admin/streamer.html', streamer_info=streamer_info)
def donations(widget_id, **options): redis = RedisManager.get() widget = redis.hget( '{streamer}:clr:donations'.format(streamer=StreamHelper.get_streamer()), widget_id) if widget is None: abort(404) tts_authentication = '' if 'extra' in config: tts_authentication = config['extra'].get('tts_authentication', '') with DBManager.create_session_scope() as db_session: emotes = db_session.query(Emote).all() return render_template('clr/donations.html', widget=json.loads(widget), emotes=emotes, tts_authentication=tts_authentication)
def social_set(social_key, **options): streamer = StreamHelper.get_streamer() if social_key not in StreamHelper.valid_social_keys: return make_response(jsonify({'error': 'invalid social key'})) if 'value' not in request.form: return make_response(jsonify({'error': 'Missing `value` parameter.'}), 400) value = request.form['value'].strip() key = '{streamer}:{key}'.format(streamer=streamer, key=social_key) redis = RedisManager.get() if len(value) == 0: redis.hdel('streamer_info', key) else: redis.hset('streamer_info', key, value) return make_response(jsonify({'message': 'success!'}))