本文整理汇总了Python中pajbot.managers.redis.RedisManager类的典型用法代码示例。如果您正苦于以下问题:Python RedisManager类的具体用法?Python RedisManager怎么用?Python RedisManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RedisManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_emotes
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'])
示例2: donations
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)
示例3: load_config
def load_config(self, config):
self.config = config
pajbot.models.user.Config.se_sync_token = config['main'].get('se_sync_token', None)
pajbot.models.user.Config.se_channel = config['main'].get('se_channel', None)
self.domain = config['web'].get('domain', 'localhost')
self.nickname = config['main'].get('nickname', 'pajbot')
self.password = config['main'].get('password', 'abcdef')
self.timezone = config['main'].get('timezone', 'UTC')
os.environ['TZ'] = self.timezone
if config['main'].getboolean('verified', False):
TMI.promote_to_verified()
self.trusted_mods = config.getboolean('main', 'trusted_mods')
self.phrases = {
'welcome': ['{nickname} {version} running!'],
'quit': ['{nickname} {version} shutting down...'],
}
if 'phrases' in config:
phrases = config['phrases']
if 'welcome' in phrases:
self.phrases['welcome'] = phrases['welcome'].splitlines()
if 'quit' in phrases:
self.phrases['quit'] = phrases['quit'].splitlines()
TimeManager.init_timezone(self.timezone)
if 'streamer' in config['main']:
self.streamer = config['main']['streamer']
self.channel = '#' + self.streamer
elif 'target' in config['main']:
self.channel = config['main']['target']
self.streamer = self.channel[1:]
self.silent = False
self.dev = False
if 'flags' in config:
self.silent = True if 'silent' in config['flags'] and config['flags']['silent'] == '1' else self.silent
self.dev = True if 'dev' in config['flags'] and config['flags']['dev'] == '1' else self.dev
DBManager.init(self.config['main']['db'])
redis_options = {}
if 'redis' in config:
redis_options = config._sections['redis']
RedisManager.init(**redis_options)
示例4: update_global_emotes
def update_global_emotes(self):
# Try to get cached global emotes from redis
_global_emotes = RedisManager.get().get('global:emotes:bttv_global')
if _global_emotes and len(_global_emotes) > 0:
log.info('Got cached BTTV global emotes!')
_global_emotes = json.loads(_global_emotes)
else:
_global_emotes = self.api.get_global_emotes()
if _global_emotes and len(_global_emotes) > 0:
RedisManager.get().setex('global:emotes:bttv_global', time=3600, value=json.dumps(_global_emotes, separators=(',', ':')))
if _global_emotes and len(_global_emotes) > 0:
self.global_emotes = {}
for emote in _global_emotes:
self.global_emotes[emote['code']] = emote['emote_hash']
示例5: __init__
def __init__(self):
super().__init__()
self.bets = {}
redis = RedisManager.get()
self.last_game_start = None
self.last_game_id = None
try:
last_game_start_timestamp = int(redis.get('{streamer}:last_hsbet_game_start'.format(streamer=StreamHelper.get_streamer())))
self.last_game_start = datetime.fromtimestamp(last_game_start_timestamp)
except (TypeError, ValueError):
# Issue with the int-cast
pass
except (OverflowError, OSError):
# Issue with datetime.fromtimestamp
pass
try:
self.last_game_id = int(redis.get('{streamer}:last_hsbet_game_id'.format(streamer=StreamHelper.get_streamer())))
except (TypeError, ValueError):
pass
self.scheduler = BackgroundScheduler()
self.scheduler.start()
self.job = self.scheduler.add_job(self.poll_trackobot, 'interval', seconds=15)
self.job.pause()
self.reminder_job = self.scheduler.add_job(self.reminder_bet, 'interval', seconds=1)
self.reminder_job.pause()
示例6: stats
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 @[email protected])
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)
示例7: __init__
def __init__(self):
super().__init__()
self.bets = {}
redis = RedisManager.get()
self.last_game_start = None
self.last_game_id = None
try:
last_game_start_timestamp = int(redis.get('{streamer}:last_hsbet_game_start'.format(streamer=StreamHelper.get_streamer())))
self.last_game_start = datetime.fromtimestamp(last_game_start_timestamp)
except (TypeError, ValueError):
# Issue with the int-cast
pass
except (OverflowError, OSError):
# Issue with datetime.fromtimestamp
pass
try:
self.last_game_id = int(redis.get('{streamer}:last_hsbet_game_id'.format(streamer=StreamHelper.get_streamer())))
except (TypeError, ValueError):
pass
self.job = ScheduleManager.execute_every(15, self.poll_trackobot)
self.job.pause()
self.reminder_job = ScheduleManager.execute_every(1, self.reminder_bet)
self.reminder_job.pause()
示例8: delete
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)
}
示例9: stop_quest
def stop_quest(self):
HandlerManager.remove_handler('on_message', self.on_message)
redis = RedisManager.get()
self.reset_progress(redis=redis)
redis.delete(self.current_emote_key)
示例10: start_quest
def start_quest(self):
HandlerManager.add_handler('on_message', self.on_message)
redis = RedisManager.get()
self.load_progress(redis=redis)
self.load_data(redis=redis)
示例11: timeout
def timeout(self, timeout_length, warning_module=None, use_warnings=True):
""" Returns a tuple with the follow data:
How long to timeout the user for, and what the punishment string is
set to.
The punishment string is used to clarify whether this was a warning or the real deal.
"""
punishment = 'timed out for {} seconds'.format(timeout_length)
if use_warnings and warning_module is not None:
redis = RedisManager.get()
""" How many chances the user has before receiving a full timeout. """
total_chances = warning_module.settings['total_chances']
warning_keys = self.get_warning_keys(total_chances, warning_module.settings['redis_prefix'])
warnings = self.get_warnings(redis, warning_keys)
chances_used = self.get_chances_used(warnings)
if chances_used < total_chances:
""" The user used up one of his warnings.
Calculate for how long we should time him out. """
timeout_length = warning_module.settings['base_timeout'] * (chances_used + 1)
punishment = 'timed out for {} seconds (warning)'.format(timeout_length)
self.add_warning(redis, warning_module.settings['length'], warning_keys, warnings)
return (timeout_length, punishment)
示例12: stop_quest
def stop_quest(self):
HandlerManager.remove_handler('on_duel_complete', self.on_duel_complete)
redis = RedisManager.get()
self.reset_progress(redis=redis)
redis.delete(self.points_required_key)
示例13: stop_quest
def stop_quest(self):
HandlerManager.remove_handler('on_user_win_hs_bet', self.on_user_win_hs_bet)
redis = RedisManager.get()
self.reset_progress(redis=redis)
redis.delete(self.hsbet_points_key)
示例14: refresh_stream_status_stage2
def refresh_stream_status_stage2(self, status):
try:
redis = RedisManager.get()
redis.hmset('stream_data', {
'{streamer}:online'.format(streamer=self.bot.streamer): status['online'],
'{streamer}:viewers'.format(streamer=self.bot.streamer): status['viewers'],
'{streamer}:game'.format(streamer=self.bot.streamer): status['game'],
})
self.num_viewers = status['viewers']
if status['online']:
if self.current_stream is None:
self.create_stream(status)
if self.current_stream_chunk is None:
self.create_stream_chunk(status)
if self.current_stream_chunk.broadcast_id != status['broadcast_id']:
log.debug('Detected a new chunk!')
self.create_stream_chunk(status)
self.num_offlines = 0
self.first_offline = None
else:
if self.online is True:
log.info('Offline. {0}'.format(self.num_offlines))
if self.first_offline is None:
self.first_offline = datetime.datetime.now()
if self.num_offlines >= 10:
log.info('Switching to offline state!')
self.go_offline()
self.num_offlines += 1
except:
log.exception('Uncaught exception while refreshing stream status (Stage 2)')
示例15: get_follow_relationship
def get_follow_relationship(self, username, streamer):
"""Returns the follow relationship between the user and a streamer.
Returns False if `username` is not following `streamer`.
Otherwise, return a datetime object.
This value is cached in Redis for 2 minutes.
"""
# XXX TODO FIXME
from pajbot.managers.redis import RedisManager
redis = RedisManager.get()
fr_key = 'fr_{username}_{streamer}'.format(username=username, streamer=streamer)
follow_relationship = redis.get(fr_key)
if follow_relationship is None:
try:
data = self.get(endpoints=['users', username, 'follows', 'channels', streamer], base=self.kraken_url)
created_at = data['created_at']
redis.setex(fr_key, time=120, value=created_at)
return TwitchAPI.parse_datetime(created_at)
except urllib.error.HTTPError:
redis.setex(fr_key, time=120, value='-1')
return False
except:
log.exception('Unhandled exception in get_follow_relationship')
return False
else:
if follow_relationship == '-1':
return False
else:
return TwitchAPI.parse_datetime(follow_relationship)