def commands(**options): from pajbot.models.command import CommandManager from pajbot.models.module import ModuleManager bot_commands = CommandManager( socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load(enabled=None) bot_commands_list = bot_commands.parse_for_web() custom_commands = [] point_commands = [] moderator_commands = [] for command in bot_commands_list: if command.id is None: continue if command.level > 100 or command.mod_only: moderator_commands.append(command) elif command.cost > 0: point_commands.append(command) else: custom_commands.append(command) with DBManager.create_session_scope() as db_session: commands_data = db_session.query(CommandData).options(joinedload(CommandData.user), joinedload(CommandData.user2)).all() return render_template( 'admin/commands.html', commands_data=commands_data, custom_commands=sorted(custom_commands, key=lambda f: f.command), point_commands=sorted(point_commands, key=lambda a: (a.cost, a.command)), moderator_commands=sorted(moderator_commands, key=lambda c: (c.level if c.mod_only is False else 500, c.command)), created=session.pop('command_created_id', None), edited=session.pop('command_edited_id', None))
def commands(**options): from pajbot.models.command import CommandManager from pajbot.models.module import ModuleManager bot_commands = CommandManager(socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load(enabled=None) bot_commands_list = bot_commands.parse_for_web() custom_commands = [] point_commands = [] moderator_commands = [] for command in bot_commands_list: if command.id is None: continue if command.level > 100 or command.mod_only: moderator_commands.append(command) elif command.cost > 0: point_commands.append(command) else: custom_commands.append(command) return render_template('admin/commands.html', custom_commands=sorted(custom_commands, key=lambda f: f.command), point_commands=sorted(point_commands, key=lambda a: (a.cost, a.command)), moderator_commands=sorted( moderator_commands, key=lambda c: (c.level if c.mod_only is False else 500, c.command)), created=session.pop('command_created_id', None), edited=session.pop('command_edited_id', None))
def update_commands(signal_id): global bot_commands_list from pajbot.models.command import CommandManager bot_commands = CommandManager( socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load(load_examples=True) bot_commands_list = bot_commands.parse_for_web() bot_commands_list = sorted(bot_commands_list, key=lambda x: (x.id or -1, x.main_alias)) del bot_commands
def update_commands(signal_id): log.debug('Updating commands...') from pajbot.models.command import CommandManager bot_commands = CommandManager( socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load(load_examples=True) app.bot_commands_list = bot_commands.parse_for_web() app.bot_commands_list.sort(key=lambda x: (x.id or -1, x.main_alias)) del bot_commands
def get_cached_commands(): CACHE_TIME = 30 # seconds redis = RedisManager.get() commands_key = '{streamer}:cache:commands'.format(streamer=StreamHelper.get_streamer()) commands = redis.get(commands_key) if commands is None: log.debug('Updating commands...') bot_commands = CommandManager( socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load(load_examples=True) bot_commands_list = bot_commands.parse_for_web() bot_commands_list.sort(key=lambda x: (x.id or -1, x.main_alias)) bot_commands_list = [c.jsonify() for c in bot_commands_list] redis.setex(commands_key, json.dumps(bot_commands_list, separators=(',', ':')), CACHE_TIME) else: bot_commands_list = json.loads(commands) return bot_commands_list
def command_checkalias(**options): if "alias" not in request.form: return make_response(jsonify({"error": "Missing `alias` parameter."}), 400) request_alias = request.form["alias"].lower() command_manager = CommandManager(socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load( enabled=None ) command_aliases = [] for alias, command in command_manager.items(): command_aliases.append(alias) if command.command and len(command.command) > 0: command_aliases.extend(command.command.split("|")) command_aliases = set(command_aliases) if request_alias in command_aliases: return make_response(jsonify({"error": "Alias already in use"})) else: return make_response(jsonify({"success": "good job"}))
def post(self, **extra_args): args = pajbot.utils.remove_none_values(self.post_parser.parse_args()) request_alias = args['alias'].lower() command_manager = CommandManager( socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load(enabled=None) command_aliases = [] for alias, command in command_manager.items(): command_aliases.append(alias) if command.command and len(command.command) > 0: command_aliases.extend(command.command.split('|')) command_aliases = set(command_aliases) if request_alias in command_aliases: return {'error': 'Alias already in use'} else: return {'success': 'good job'}
def command_checkalias(**options): if 'alias' not in request.form: return make_response(jsonify({'error': 'Missing `alias` parameter.'}), 400) request_alias = request.form['alias'].lower() command_manager = CommandManager( socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load(enabled=None) command_aliases = [] for alias, command in command_manager.items(): command_aliases.append(alias) if command.command and len(command.command) > 0: command_aliases.extend(command.command.split('|')) command_aliases = set(command_aliases) if request_alias in command_aliases: return make_response(jsonify({'error': 'Alias already in use'})) else: return make_response(jsonify({'success': 'good job'}))
def commands_create(**options): session.pop('command_created_id', None) session.pop('command_edited_id', None) if request.method == 'POST': if 'aliases' not in request.form: abort(403) alias_str = request.form.get('aliases', '').replace('!', '').lower() delay_all = request.form.get('cd', Command.DEFAULT_CD_ALL) delay_user = request.form.get('usercd', Command.DEFAULT_CD_USER) level = request.form.get('level', Command.DEFAULT_LEVEL) cost = request.form.get('cost', 0) try: delay_all = int(delay_all) delay_user = int(delay_user) level = int(level) cost = int(cost) except ValueError: abort(403) if len(alias_str) == 0: abort(403) if delay_all < 0 or delay_all > 9999: abort(403) if delay_user < 0 or delay_user > 9999: abort(403) if level < 0 or level > 2000: abort(403) if cost < 0 or cost > 9999999: abort(403) options = { 'delay_all': delay_all, 'delay_user': delay_user, 'level': level, 'cost': cost, } valid_action_types = ['say', 'me', 'whisper', 'reply'] action_type = request.form.get('reply', 'say').lower() if action_type not in valid_action_types: abort(403) response = request.form.get('response', '') if len(response) == 0: abort(403) action = { 'type': action_type, 'message': response } options['action'] = action command_manager = CommandManager( socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load(enabled=None) command_aliases = [] for alias, command in command_manager.items(): command_aliases.append(alias) if command.command and len(command.command) > 0: command_aliases.extend(command.command.split('|')) command_aliases = set(command_aliases) alias_str = alias_str.replace(' ', '').replace('!', '').lower() alias_list = alias_str.split('|') alias_list = [alias for alias in alias_list if len(alias) > 0] if len(alias_list) == 0: return render_template('admin/create_command_fail.html') for alias in alias_list: if alias in command_aliases: return render_template('admin/create_command_fail.html') alias_str = '|'.join(alias_list) command = Command(command=alias_str, **options) command.data = CommandData(command.id) with DBManager.create_session_scope(expire_on_commit=False) as db_session: db_session.add(command) db_session.add(command.data) db_session.commit() db_session.expunge(command) db_session.expunge(command.data) SocketClientManager.send('command.update', {'command_id': command.id}) session['command_created_id'] = command.id return redirect('/admin/commands/', 303) else: return render_template('admin/create_command.html')
def commands_create(**options): session.pop('command_created_id', None) session.pop('command_edited_id', None) if request.method == 'POST': if 'aliases' not in request.form: abort(403) alias_str = request.form.get('aliases', '').replace('!', '').lower() delay_all = request.form.get('cd', Command.DEFAULT_CD_ALL) delay_user = request.form.get('usercd', Command.DEFAULT_CD_USER) level = request.form.get('level', Command.DEFAULT_LEVEL) cost = request.form.get('cost', 0) try: delay_all = int(delay_all) delay_user = int(delay_user) level = int(level) cost = int(cost) except ValueError: abort(403) if len(alias_str) == 0: abort(403) if delay_all < 0 or delay_all > 9999: abort(403) if delay_user < 0 or delay_user > 9999: abort(403) if level < 0 or level > 2000: abort(403) if cost < 0 or cost > 9999999: abort(403) options = { 'delay_all': delay_all, 'delay_user': delay_user, 'level': level, 'cost': cost, } valid_action_types = ['say', 'me', 'whisper', 'reply'] action_type = request.form.get('reply', 'say').lower() if action_type not in valid_action_types: abort(403) response = request.form.get('response', '') if len(response) == 0: abort(403) action = {'type': action_type, 'message': response} options['action'] = action command_manager = CommandManager( socket_manager=None, module_manager=ModuleManager(None).load(), bot=None).load(enabled=None) command_aliases = [] for alias, command in command_manager.items(): command_aliases.append(alias) if command.command and len(command.command) > 0: command_aliases.extend(command.command.split('|')) command_aliases = set(command_aliases) alias_str = alias_str.replace(' ', '').replace('!', '').lower() alias_list = alias_str.split('|') alias_list = [alias for alias in alias_list if len(alias) > 0] if len(alias_list) == 0: return render_template('admin/create_command_fail.html') for alias in alias_list: if alias in command_aliases: return render_template('admin/create_command_fail.html') alias_str = '|'.join(alias_list) command = Command(command=alias_str, **options) command.data = CommandData(command.id) with DBManager.create_session_scope( expire_on_commit=False) as db_session: db_session.add(command) db_session.add(command.data) db_session.commit() db_session.expunge(command) db_session.expunge(command.data) SocketClientManager.send('command.update', {'command_id': command.id}) session['command_created_id'] = command.id return redirect('/admin/commands/', 303) else: return render_template('admin/create_command.html')
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): 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)