本文整理汇总了Python中pajbot.managers.handler.HandlerManager.trigger方法的典型用法代码示例。如果您正苦于以下问题:Python HandlerManager.trigger方法的具体用法?Python HandlerManager.trigger怎么用?Python HandlerManager.trigger使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pajbot.managers.handler.HandlerManager
的用法示例。
在下文中一共展示了HandlerManager.trigger方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_stream
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def create_stream(self, status):
log.info('Attempting to create a stream!')
with DBManager.create_session_scope(expire_on_commit=False) as db_session:
stream_chunk = db_session.query(StreamChunk).filter_by(broadcast_id=status['broadcast_id']).one_or_none()
new_stream = False
if stream_chunk is not None:
stream = stream_chunk.stream
else:
log.info('checking if there is an active stream already')
stream = db_session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start.desc()).first()
new_stream = stream is None
if new_stream:
log.info('No active stream, create new!')
stream = Stream(status['created_at'],
title=status['title'])
db_session.add(stream)
db_session.commit()
log.info('Successfully added stream!')
stream_chunk = StreamChunk(stream, status['broadcast_id'], status['created_at'])
db_session.add(stream_chunk)
db_session.commit()
stream.stream_chunks.append(stream_chunk)
log.info('Created stream chunk')
self.current_stream = stream
self.current_stream_chunk = stream_chunk
db_session.expunge_all()
if new_stream:
HandlerManager.trigger('on_stream_start', stop_on_false=False)
log.info('Successfully created a stream')
示例2: on_usernotice
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def on_usernotice(self, source, message, tags):
if 'msg-id' not in tags or 'msg-param-months' not in tags:
return
if tags['msg-id'] == 'resub':
num_months = int(tags['msg-param-months'])
self.on_resub(source, num_months)
HandlerManager.trigger('on_user_resub', source, num_months)
示例3: base_paid_timeout
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def base_paid_timeout(self, bot, source, message, _time, _cost):
if message is None or len(message) == 0:
return False
target = message.split(' ')[0]
if len(target) < 2:
return False
with bot.users.find_context(target) as victim:
if victim is None:
bot.whisper(source.username, 'This user does not exist FailFish')
return False
if victim.last_active is None or (datetime.datetime.now() - victim._last_active).total_seconds() > 10 * 60:
bot.whisper(source.username, 'This user has not been active in chat within the last 10 minutes.')
return False
"""
if victim == source:
bot.whisper(source.username, 'You can\'t timeout yourself FailFish')
return False
"""
if victim.moderator is True:
bot.whisper(source.username, 'This person has mod privileges, timeouting this person is not worth it.')
return False
if victim.level >= self.settings['bypass_level']:
bot.whisper(source.username, 'This person\'s user level is too high, you can\'t timeout this person.')
return False
now = datetime.datetime.now()
if victim.timed_out is True and victim.timeout_end > now:
victim.timeout_end += datetime.timedelta(seconds=_time)
bot.whisper(victim.username, '{victim.username}, you were timed out for an additional {time} seconds by {source.username}'.format(
victim=victim,
source=source,
time=_time))
bot.whisper(source.username, 'You just used {0} points to time out {1} for an additional {2} seconds.'.format(_cost, victim.username, _time))
num_seconds = int((victim.timeout_end - now).total_seconds())
bot._timeout(victim.username, num_seconds, reason='Timed out by {}'.format(source.username_raw))
# songs = session.query(PleblistSong, func.count(PleblistSong.song_info).label('total')).group_by(PleblistSong.youtube_id).order_by('total DESC')
else:
bot.whisper(source.username, 'You just used {0} points to time out {1} for {2} seconds.'.format(_cost, victim.username, _time))
bot.whisper(victim.username, '{0} just timed you out for {1} seconds. /w {2} !$unbanme to unban yourself for points forsenMoney'.format(source.username, _time, bot.nickname))
bot._timeout(victim.username, _time, reason='Timed out by {}'.format(source.username_raw))
victim.timed_out = True
victim.timeout_start = now
victim.timeout_end = now + datetime.timedelta(seconds=_time)
if self.settings['show_on_clr']:
payload = {'user': source.username, 'victim': victim.username}
bot.websocket_manager.emit('timeout', payload)
HandlerManager.trigger('on_paid_timeout',
source, victim, _cost,
stop_on_false=False)
示例4: commit_all
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def commit_all(self):
log.info('Commiting all...')
for key, manager in self.commitable.items():
log.info('Commiting {0}'.format(key))
manager.commit()
log.info('Done with {0}'.format(key))
log.info('ok!')
HandlerManager.trigger('on_commit', stop_on_false=False)
示例5: on_message
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def on_message(self, source, message, emotes, whisper, urls, event):
if whisper is False and source.username in self.valid_usernames:
# Did twitchnotify tell us about a new sub?
m = self.new_sub_regex.search(message)
if m:
username = m.group(1)
with UserManager.get().get_user_context(username) as user:
self.on_new_sub(user)
HandlerManager.trigger('on_user_sub', user)
示例6: parse_message
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def parse_message(self, msg_raw, source, event, tags={}, whisper=False):
msg_lower = msg_raw.lower()
emote_tag = None
for tag in tags:
if tag['key'] == 'subscriber' and event.target == self.channel:
source.subscriber = tag['value'] == '1'
elif tag['key'] == 'emotes' and tag['value']:
emote_tag = tag['value']
elif tag['key'] == 'display-name' and tag['value']:
source.username_raw = tag['value']
elif tag['key'] == 'user-type':
source.moderator = tag['value'] == 'mod' or source.username == self.streamer
# source.num_lines += 1
if source is None:
log.error('No valid user passed to parse_message')
return False
if source.banned:
self.ban(source.username)
return False
# If a user types when timed out, we assume he's been unbanned for a good reason and remove his flag.
if source.timed_out is True:
source.timed_out = False
# Parse emotes in the message
message_emotes = self.emotes.parse_message_twitch_emotes(source, msg_raw, emote_tag, whisper)
urls = self.find_unique_urls(msg_raw)
log.debug('{2}{0}: {1}'.format(source.username, msg_raw, '<w>' if whisper else ''))
res = HandlerManager.trigger('on_message',
source, msg_raw, message_emotes, whisper, urls, event,
stop_on_false=True)
if res is False:
return False
source.last_seen = datetime.datetime.now()
source.last_active = datetime.datetime.now()
if source.ignored:
return False
if msg_lower[:1] == '!':
msg_lower_parts = msg_lower.split(' ')
trigger = msg_lower_parts[0][1:]
msg_raw_parts = msg_raw.split(' ')
remaining_message = ' '.join(msg_raw_parts[1:]) if len(msg_raw_parts) > 1 else None
if trigger in self.commands:
command = self.commands[trigger]
extra_args = {
'emotes': message_emotes,
'trigger': trigger,
}
command.run(self, source, remaining_message, event=event, args=extra_args, whisper=whisper)
示例7: on_usernotice
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def on_usernotice(self, chatconn, event):
# We use .lower() in case twitch ever starts sending non-lowercased usernames
tags = {}
for d in event.tags:
tags[d['key']] = d['value']
if 'login' not in tags:
return
username = tags['login']
with self.users.get_user_context(username) as source:
msg = ''
if len(event.arguments) > 0:
msg = event.arguments[0]
HandlerManager.trigger('on_usernotice',
source, msg, tags)
示例8: go_offline
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def go_offline(self):
with DBManager.create_session_scope(expire_on_commit=False) as db_session:
self.current_stream.ended = True
self.current_stream.stream_end = self.first_offline
self.current_stream_chunk.chunk_end = self.first_offline
db_session.add(self.current_stream)
db_session.add(self.current_stream_chunk)
db_session.commit()
db_session.expunge_all()
self.last_stream = self.current_stream
self.current_stream = None
self.current_stream_chunk = None
HandlerManager.trigger('on_stream_stop', stop_on_false=False)
示例9: end_raffle
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def end_raffle(self):
if not self.raffle_running:
return False
self.raffle_running = False
if len(self.raffle_users) == 0:
self.bot.me('Wow, no one joined the raffle DansGame')
return False
winner = random.choice(self.raffle_users)
self.raffle_users = []
if self.settings['show_on_clr']:
self.bot.websocket_manager.emit('notification', {'message': '{} won {} points in the raffle!'.format(winner.username_raw, self.raffle_points)})
self.bot.me('The raffle has finished! {0} won {1} points! PogChamp'.format(winner.username_raw, self.raffle_points))
winner.points += self.raffle_points
winner.save()
HandlerManager.trigger('on_raffle_win', winner, self.raffle_points)
示例10: on_pubmsg
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def on_pubmsg(self, chatconn, event):
if event.source.user == self.nickname:
return False
username = event.source.user.lower()
# We use .lower() in case twitch ever starts sending non-lowercased usernames
with self.users.get_user_context(username) as source:
res = HandlerManager.trigger('on_pubmsg',
source, event.arguments[0],
stop_on_false=True)
if res is False:
return False
self.parse_message(event.arguments[0], source, event, tags=event.tags)
示例11: on_pubmsg
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def on_pubmsg(self, chatconn, event):
if event.source.user == self.nickname:
return False
username = event.source.user.lower()
if self.streamer == 'forsen':
if 'zonothene' in username:
self._ban(username)
return True
raw_m = event.arguments[0].lower()
if raw_m.startswith('!lastseen forsen'):
if len(raw_m) > len('!lastseen forsen2'):
if raw_m[16] == ' ':
return True
else:
return True
if raw_m.startswith('!lastseen @forsen'):
if len(raw_m) > len('!lastseen @forsen2'):
if raw_m[17] == ' ':
return True
else:
return True
if self.streamer == 'nymn':
if 'hades_k' in username:
self._timeout(username, 3600)
return True
if 'hades_b' in username:
self._timeout(username, 3600)
return True
raw_m = event.arguments[0]
m = ''.join(sorted(set(raw_m), key=raw_m.index))
m = ''.join(ch for ch in m if ch.isalnum())
if 'niqers' in m:
self.timeout(username, 600)
return True
if 'niqe3rs' in m:
self.timeout(username, 600)
return True
if 'niq3ers' in m:
self.timeout(username, 600)
return True
if 'niqurs' in m:
self.timeout(username, 600)
return True
if 'nigurs' in m:
self.timeout(username, 600)
return True
if 'nige3rs' in m:
self.timeout(username, 600)
return True
if 'nig3ers' in m:
self.timeout(username, 600)
return True
if 'nig3ers' in m:
self.timeout(username, 600)
return True
if 'nigger' in m:
self.timeout(username, 600)
return True
# We use .lower() in case twitch ever starts sending non-lowercased usernames
with self.users.get_user_context(username) as source:
res = HandlerManager.trigger('on_pubmsg',
source, event.arguments[0],
stop_on_false=True)
if res is False:
return False
self.parse_message(event.arguments[0], source, event, tags=event.tags)
示例12: __init__
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def __init__(self, config, args=None):
# Load various configuration variables from the given config object
# The config object that should be passed through should
# come from pajbot.utils.load_config
self.load_config(config)
# Update the database scheme if necessary using alembic
# In case of errors, i.e. if the database is out of sync or the alembic
# binary can't be called, we will shut down the bot.
pajbot.utils.alembic_upgrade()
# Actions in this queue are run in a separate thread.
# This means actions should NOT access any database-related stuff.
self.action_queue = ActionQueue()
self.action_queue.start()
self.reactor = irc.client.Reactor(self.on_connect)
self.start_time = datetime.datetime.now()
ActionParser.bot = self
HandlerManager.init_handlers()
self.socket_manager = SocketManager(self)
self.stream_manager = StreamManager(self)
StreamHelper.init_bot(self, self.stream_manager)
ScheduleManager.init()
self.users = UserManager()
self.decks = DeckManager()
self.module_manager = ModuleManager(self.socket_manager, bot=self).load()
self.commands = CommandManager(
socket_manager=self.socket_manager,
module_manager=self.module_manager,
bot=self).load()
self.filters = FilterManager().reload()
self.banphrase_manager = BanphraseManager(self).load()
self.timer_manager = TimerManager(self).load()
self.kvi = KVIManager()
self.emotes = EmoteManager(self)
self.twitter_manager = TwitterManager(self)
HandlerManager.trigger('on_managers_loaded')
# Reloadable managers
self.reloadable = {
'filters': self.filters,
}
# Commitable managers
self.commitable = {
'commands': self.commands,
'filters': self.filters,
'banphrases': self.banphrase_manager,
}
self.execute_every(10 * 60, self.commit_all)
self.execute_every(1, self.do_tick)
try:
self.admin = self.config['main']['admin']
except KeyError:
log.warning('No admin user specified. See the [main] section in config.example.ini for its usage.')
if self.admin:
with self.users.get_user_context(self.admin) as user:
user.level = 2000
self.parse_version()
relay_host = self.config['main'].get('relay_host', None)
relay_password = self.config['main'].get('relay_password', None)
if relay_host is None or relay_password is None:
self.irc = MultiIRCManager(self)
else:
self.irc = SingleIRCManager(self)
self.reactor.add_global_handler('all_events', self.irc._dispatcher, -10)
twitch_client_id = None
twitch_oauth = None
if 'twitchapi' in self.config:
twitch_client_id = self.config['twitchapi'].get('client_id', None)
twitch_oauth = self.config['twitchapi'].get('oauth', None)
# A client ID is required for the bot to work properly now, give an error for now
if twitch_client_id is None:
log.error('MISSING CLIENT ID, SET "client_id" VALUE UNDER [twitchapi] SECTION IN CONFIG FILE')
self.twitchapi = TwitchAPI(twitch_client_id, twitch_oauth)
self.data = {}
self.data_cb = {}
self.url_regex = re.compile(self.url_regex_str, re.IGNORECASE)
self.data['broadcaster'] = self.streamer
self.data['version'] = self.version
self.data['version_brief'] = self.version_brief
self.data['bot_name'] = self.nickname
self.data_cb['status_length'] = self.c_status_length
self.data_cb['stream_status'] = self.c_stream_status
#.........这里部分代码省略.........
示例13: poll_trackobot_stage2
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def poll_trackobot_stage2(self, game_data):
latest_game = game_data['history'][0]
if latest_game['id'] != self.last_game_id:
# A new game has been detected
# Reset all variables
winners = []
losers = []
total_winning_points = 0
total_losing_points = 0
points_bet = {
'win': 0,
'loss': 0,
}
bet_game_id = None
# Mark down the last game's results
with DBManager.create_session_scope() as db_session:
bet_game = HSBetGame(latest_game['id'], latest_game['result'])
db_session.add(bet_game)
db_session.flush()
bet_game_id = bet_game.id
db_bets = {}
for username in self.bets:
bet_for_win, points = self.bets[username]
"""
self.bot.me('{} bet {} points on the last game to end up as a {}'.format(
username,
points,
'win' if bet_for_win else 'loss'))
"""
user = self.bot.users.find(username, db_session=db_session)
if user is None:
continue
correct_bet = (latest_game['result'] == 'win' and bet_for_win is True) or (latest_game['result'] == 'loss' and bet_for_win is False)
points_bet['win' if bet_for_win else 'loss'] += points
db_bets[username] = HSBetBet(bet_game_id, user.id, 'win' if bet_for_win else 'loss', points, 0)
if correct_bet:
winners.append((user, points))
total_winning_points += points
user.remove_debt(points)
else:
losers.append((user, points))
total_losing_points += points
user.pay_debt(points)
db_bets[username].profit = -points
self.bot.whisper(user.username, 'You bet {} points on the wrong outcome, so you lost it all. :('.format(
points))
for obj in losers:
user, points = obj
user.save()
log.debug('{} lost {} points!'.format(user, points))
for obj in winners:
points_reward = 0
user, points = obj
if points == 0:
# If you didn't bet any points, you don't get a part of the cut.
HandlerManager.trigger('on_user_win_hs_bet', user, points_reward)
continue
pot_cut = points / total_winning_points
points_reward = int(pot_cut * total_losing_points)
db_bets[user.username].profit = points_reward
user.points += points_reward
user.save()
HandlerManager.trigger('on_user_win_hs_bet', user, points_reward)
self.bot.whisper(user.username, 'You bet {} points on the right outcome, that rewards you with a profit of {} points! (Your bet was {:.2f}% of the total pool)'.format(
points, points_reward, pot_cut * 100))
"""
self.bot.me('{} bet {} points, and made a profit of {} points by correctly betting on the HS game!'.format(
user.username_raw, points, points_reward))
"""
for username in db_bets:
bet = db_bets[username]
db_session.add(bet)
self.bot.me('A new game has begun! Vote with !hsbet win/lose POINTS')
self.bets = {}
self.last_game_id = latest_game['id']
self.last_game_start = datetime.datetime.now() + datetime.timedelta(seconds=self.settings['time_until_bet_closes'])
payload = {
'time_left': self.settings['time_until_bet_closes'],
'win': 0,
'loss': 0,
}
self.bot.websocket_manager.emit('hsbet_new_game', data=payload)
# stats about the game
ratio = 0.0
try:
ratio = (total_losing_points / total_winning_points) * 100.0
#.........这里部分代码省略.........
示例14: do_tick
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def do_tick(self):
HandlerManager.trigger('on_tick')
示例15: multi_end_raffle
# 需要导入模块: from pajbot.managers.handler import HandlerManager [as 别名]
# 或者: from pajbot.managers.handler.HandlerManager import trigger [as 别名]
def multi_end_raffle(self):
if not self.raffle_running:
return False
self.raffle_running = False
if len(self.raffle_users) == 0:
self.bot.me('Wow, no one joined the raffle DansGame')
return False
# Shuffle the list of participants
random.shuffle(self.raffle_users)
num_participants = len(self.raffle_users)
abs_points = abs(self.raffle_points)
max_winners = min(num_participants, 200)
min_point_award = 100
negative = self.raffle_points < 0
# Decide how we should pick the winners
log.info('Num participants: {}'.format(num_participants))
for winner_percentage in [x * 0.01 for x in range(1, 26)]:
log.info('Winner percentage: {}'.format(winner_percentage))
num_winners = math.ceil(num_participants * winner_percentage)
points_per_user = math.ceil(abs_points / num_winners)
log.info('nw: {}, ppu: {}'.format(num_winners, points_per_user))
if num_winners > max_winners:
num_winners = max_winners
points_per_user = math.ceil(abs_points / num_winners)
break
elif points_per_user < min_point_award:
num_winners = max(1, min(math.floor(abs_points / min_point_award), num_participants))
points_per_user = math.ceil(abs_points / num_winners)
break
log.info('k done. got {} winners'.format(num_winners))
winners = self.raffle_users[:num_winners]
self.raffle_users = []
if negative:
points_per_user *= -1
self.bot.me('The multi-raffle has finished! {0} users won {1} points each! PogChamp'.format(len(winners), points_per_user))
winners_arr = []
for winner in winners:
winner.points += points_per_user
winners_arr.append(winner)
winners_str = generate_winner_list(winners_arr)
if len(winners_str) > 300:
self.bot.me('{} won {} points each!'.format(winners_str, points_per_user))
winners_arr = []
winner.save()
if len(winners_arr) > 0:
winners_str = generate_winner_list(winners_arr)
self.bot.me('{} won {} points each!'.format(winners_str, points_per_user))
HandlerManager.trigger('on_multiraffle_win', winners, points_per_user)