def pleblist_add_song(self, **options): message = options['message'] bot = options['bot'] source = options['source'] if message: # 1. Find youtube ID in message msg_split = message.split(' ') youtube_id = find_youtube_id_in_string(msg_split[0]) force = False try: if msg_split[1] == 'force' and source.level >= 500: force = True except: pass if youtube_id is False: bot.whisper(source.username, 'Could not find a valid youtube ID in your argument.') return False # 2. Make sure the stream is live stream_id = StreamHelper.get_current_stream_id() if stream_id is None or stream_id is False: bot.whisper(source.username, 'You cannot request songs while the stream is offline.') return False ScheduleManager.execute_now(self.bg_pleblist_add_song, args=[stream_id, youtube_id, force], kwargs=options)
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()
def run(self, bot, source, message, event={}, args={}, whisper=False): if self.action is None: log.warning('This command is not available.') return False if source.level < self.level: # User does not have a high enough power level to run this command return False if whisper and self.can_execute_with_whisper is False and source.level < Command.MIN_WHISPER_LEVEL and source.moderator is False: # This user cannot execute the command through a whisper return False if self.sub_only and source.subscriber is False and source.level < Command.BYPASS_SUB_ONLY_LEVEL and source.moderator is False: # User is not a sub or a moderator, and cannot use the command. return False if self.mod_only and source.moderator is False and source.level < Command.BYPASS_MOD_ONLY_LEVEL: # User is not a twitch moderator, or a bot moderator return False cd_modifier = 0.2 if source.level >= 500 or source.moderator is True else 1.0 cur_time = time.time() time_since_last_run = (cur_time - self.last_run) / cd_modifier if time_since_last_run < self.delay_all and source.level < Command.BYPASS_DELAY_LEVEL: log.debug('Command was run {0:.2f} seconds ago, waiting...'.format( time_since_last_run)) return False time_since_last_run_user = (cur_time - self.last_run_by_user.get( source.username, 0)) / cd_modifier if time_since_last_run_user < self.delay_user and source.level < Command.BYPASS_DELAY_LEVEL: log.debug('{0} ran command {1:.2f} seconds ago, waiting...'.format( source.username, time_since_last_run_user)) return False if self.cost > 0 and not source.can_afford(self.cost): # User does not have enough points to use the command return False if self.tokens_cost > 0 and not source.can_afford_with_tokens( self.tokens_cost): # User does not have enough tokens to use the command return False args.update(self.extra_args) if self.run_in_thread: log.debug('Running {} in a thread'.format(self)) ScheduleManager.execute_now( self.run_action, args=[bot, source, message, event, args]) else: self.run_action(bot, source, message, event, args)
def run(self, bot, source, message, event={}, args={}, whisper=False): if self.action is None: log.warning('This command is not available.') return False if source.level < self.level: # User does not have a high enough power level to run this command return False if whisper and self.can_execute_with_whisper is False and source.level < Command.MIN_WHISPER_LEVEL and source.moderator is False: # This user cannot execute the command through a whisper return False if self.sub_only and source.subscriber is False and source.level < Command.BYPASS_SUB_ONLY_LEVEL and source.moderator is False: # User is not a sub or a moderator, and cannot use the command. return False if self.mod_only and source.moderator is False and source.level < Command.BYPASS_MOD_ONLY_LEVEL: # User is not a twitch moderator, or a bot moderator return False cd_modifier = 0.2 if source.level >= 500 or source.moderator is True else 1.0 cur_time = time.time() time_since_last_run = (cur_time - self.last_run) / cd_modifier if time_since_last_run < self.delay_all and source.level < Command.BYPASS_DELAY_LEVEL: log.debug('Command was run {0:.2f} seconds ago, waiting...'.format(time_since_last_run)) return False time_since_last_run_user = (cur_time - self.last_run_by_user.get(source.username, 0)) / cd_modifier if time_since_last_run_user < self.delay_user and source.level < Command.BYPASS_DELAY_LEVEL: log.debug('{0} ran command {1:.2f} seconds ago, waiting...'.format(source.username, time_since_last_run_user)) return False if self.cost > 0 and not source.can_afford(self.cost): # User does not have enough points to use the command return False if self.tokens_cost > 0 and not source.can_afford_with_tokens(self.tokens_cost): # User does not have enough tokens to use the command return False args.update(self.extra_args) if self.run_in_thread: log.debug('Running {} in a thread'.format(self)) ScheduleManager.execute_now(self.run_action, args=[bot, source, message, event, args]) else: self.run_action(bot, source, message, event, args)
def pleblist_add_song(self, **options): message = options['message'] bot = options['bot'] source = options['source'] if message: # 1. Find youtube ID in message msg_split = message.split(' ') youtube_id = find_youtube_id_in_string(msg_split[0]) if youtube_id is False: bot.whisper(source.username, 'Could not find a valid youtube ID in your argument.') return False # 2. Make sure the stream is live stream_id = StreamHelper.get_current_stream_id() if stream_id is None or stream_id is False: bot.whisper(source.username, 'You cannot request songs while the stream is offline.') return False ScheduleManager.execute_now(self.bg_pleblist_add_song, args=[stream_id, youtube_id], kwargs=options)
def __init__(self): super().__init__() self.job = ScheduleManager.execute_every(1, self.poll_trivia) self.job.pause() self.trivia_running = False self.last_question = None self.question = None self.step = 0 self.last_step = None self.point_bounty = 0
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.tbutil.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) self.duel_manager = DuelManager(self) HandlerManager.trigger('on_managers_loaded') # Reloadable managers self.reloadable = { 'filters': self.filters, } # Commitable managers self.commitable = { 'commands': self.commands, 'filters': self.filters, 'users': self.users, 'banphrases': self.banphrase_manager, } self.execute_every(10 * 60, self.commit_all) 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: self.users[self.admin].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) self.twitchapi = TwitchAPI(twitch_client_id, twitch_oauth) self.ascii_timeout_duration = 120 self.msg_length_timeout_duration = 120 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_cb['status_length'] = self.c_status_length self.data_cb['stream_status'] = self.c_stream_status self.data_cb['bot_uptime'] = self.c_uptime self.data_cb['current_time'] = self.c_current_time self.silent = True if args.silent else self.silent if self.silent: log.info('Silent mode enabled') self.reconnection_interval = 5 """ For actions that need to access the main thread, we can use the mainthread_queue. """ self.mainthread_queue = ActionQueue() self.execute_every(1, self.mainthread_queue.parse_action) self.websocket_manager = WebSocketManager(self) try: if self.config['twitchapi']['update_subscribers'] == '1': self.execute_every(30 * 60, self.action_queue.add, (self.update_subscribers_stage1, )) except: pass # XXX: TEMPORARY UGLY CODE HandlerManager.add_handler('on_user_gain_tokens', self.on_user_gain_tokens)
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.tbutil.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) 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) self.twitchapi = TwitchAPI(twitch_client_id, twitch_oauth) self.ascii_timeout_duration = 120 self.msg_length_timeout_duration = 120 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_cb['status_length'] = self.c_status_length self.data_cb['stream_status'] = self.c_stream_status self.data_cb['bot_uptime'] = self.c_uptime self.data_cb['current_time'] = self.c_current_time self.silent = True if args.silent else self.silent if self.silent: log.info('Silent mode enabled') self.reconnection_interval = 5 """ For actions that need to access the main thread, we can use the mainthread_queue. """ self.mainthread_queue = ActionQueue() self.execute_every(1, self.mainthread_queue.parse_action) self.websocket_manager = WebSocketManager(self) try: if self.config['twitchapi']['update_subscribers'] == '1': self.execute_every(30 * 60, self.action_queue.add, (self.update_subscribers_stage1, )) except: pass # XXX: TEMPORARY UGLY CODE HandlerManager.add_handler('on_user_gain_tokens', self.on_user_gain_tokens)
def __init__(self, config, args=None): self.load_config(config) self.last_ping = datetime.datetime.now() self.last_pong = datetime.datetime.now() self.load_default_phrases() self.db_session = DBManager.create_session() try: subprocess.check_call( ['alembic', 'upgrade', 'head'] + ['--tag="{0}"'.format(' '.join(sys.argv[1:]))]) except subprocess.CalledProcessError: log.exception('aaaa') log.error( 'Unable to call `alembic upgrade head`, this means the database could be out of date. Quitting.' ) sys.exit(1) except PermissionError: log.error( 'No permission to run `alembic upgrade head`. This means your user probably doesn\'t have execution rights on the `alembic` binary.' ) log.error( 'The error can also occur if it can\'t find `alembic` in your PATH, and instead tries to execute the alembic folder.' ) sys.exit(1) except FileNotFoundError: log.error( 'Could not found an installation of alembic. Please install alembic to continue.' ) sys.exit(1) except: log.exception('Unhandled exception when calling db update') sys.exit(1) # 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).reload() self.twitter_manager = TwitterManager(self) self.duel_manager = DuelManager(self) HandlerManager.trigger('on_managers_loaded') # Reloadable managers self.reloadable = { 'filters': self.filters, 'emotes': self.emotes, } # Commitable managers self.commitable = { 'commands': self.commands, 'filters': self.filters, 'emotes': self.emotes, 'users': self.users, 'banphrases': self.banphrase_manager, } self.execute_every(10 * 60, self.commit_all) 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: self.users[self.admin].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) self.twitchapi = TwitchAPI(twitch_client_id, twitch_oauth) self.ascii_timeout_duration = 120 self.msg_length_timeout_duration = 120 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_cb['status_length'] = self.c_status_length self.data_cb['stream_status'] = self.c_stream_status self.data_cb['bot_uptime'] = self.c_uptime self.data_cb['current_time'] = self.c_current_time self.silent = True if args.silent else self.silent if self.silent: log.info('Silent mode enabled') self.reconnection_interval = 5 """ For actions that need to access the main thread, we can use the mainthread_queue. """ self.mainthread_queue = ActionQueue() self.execute_every(1, self.mainthread_queue.parse_action) self.websocket_manager = WebSocketManager(self) try: if self.config['twitchapi']['update_subscribers'] == '1': self.execute_every(30 * 60, self.action_queue.add, (self.update_subscribers_stage1, )) except: pass # XXX: TEMPORARY UGLY CODE HandlerManager.add_handler('on_user_gain_tokens', self.on_user_gain_tokens)