Exemple #1
0
    def level(self, **options):
        message = options['message']
        bot = options['bot']
        source = options['source']

        if message:
            msg_args = message.split(' ')
            if len(msg_args) > 1:
                username = msg_args[0].lower()
                new_level = int(msg_args[1])
                if new_level >= source.level:
                    bot.whisper(source.username, 'You cannot promote someone to the same or higher level as you ({0}).'.format(source.level))
                    return False

                # We create the user if the user didn't already exist in the database.
                with bot.users.get_user_context(username) as user:
                    old_level = user.level
                    user.level = new_level

                    log_msg = '{}\'s user level changed from {} to {}'.format(
                            user.username_raw,
                            old_level,
                            new_level)

                    bot.whisper(source.username, log_msg)

                    AdminLogManager.add_entry('Userlevel edited', source, log_msg)

                    return True

        bot.whisper(source.username, 'Usage: !level USERNAME NEW_LEVEL')
        return False
Exemple #2
0
    def level(self, **options):
        message = options['message']
        bot = options['bot']
        source = options['source']

        if message:
            msg_args = message.split(' ')
            if len(msg_args) > 1:
                username = msg_args[0].lower()
                new_level = int(msg_args[1])
                if new_level >= source.level:
                    bot.whisper(source.username, 'You cannot promote someone to the same or higher level as you ({0}).'.format(source.level))
                    return False

                # We create the user if the user didn't already exist in the database.
                user = bot.users[username]

                old_level = user.level
                user.level = new_level

                log_msg = '{}\'s user level changed from {} to {}'.format(
                        user.username_raw,
                        old_level,
                        new_level)

                bot.whisper(source.username, log_msg)

                AdminLogManager.add_entry('Userlevel edited', source, log_msg)

                return True

        bot.whisper(source.username, 'Usage: !level USERNAME NEW_LEVEL')
        return False
Exemple #3
0
def command_remove(command_id, **options):
    with DBManager.create_session_scope() as db_session:
        command = db_session.query(Command).filter_by(id=command_id).one_or_none()
        if command is None:
            return make_response(jsonify({'error': 'Invalid command ID'}), 404)
        if command.level > options['user'].level:
            abort(403)
        log_msg = 'The !{} command has been removed'.format(command.command.split('|')[0])
        AdminLogManager.add_entry('Command removed',
                options['user'],
                log_msg)
        db_session.delete(command.data)
        db_session.delete(command)

    payload = {
            'event': 'command.remove',
            'data': {
                'command_id': command_id
                }
            }
    payload_bytes = json.dumps(payload).encode('utf-8')
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
            client.connect(config['sock']['sock_file'])
            client.sendall(payload_bytes)
            return make_response(jsonify({'success': 'good job'}))
    except:
        log.exception('???')
        return make_response(jsonify({'error': 'Could not push update'}))
Exemple #4
0
    def level(bot, source, message, event, args):
        if message:
            msg_args = message.split(' ')
            if len(msg_args) > 1:
                username = msg_args[0].lower()
                new_level = int(msg_args[1])
                if new_level >= source.level:
                    bot.whisper(source.username, 'You cannot promote someone to the same or higher level as you ({0}).'.format(source.level))
                    return False

                # We create the user if the user didn't already exist in the database.
                user = bot.users[username]

                old_level = user.level
                user.level = new_level

                log_msg = '{}\'s user level changed from {} to {}'.format(
                        user.username_raw,
                        old_level,
                        new_level)

                bot.whisper(source.username, log_msg)

                AdminLogManager.add_entry('Userlevel edited', source, log_msg)

                return True

        bot.whisper(source.username, 'Usage: !level USERNAME NEW_LEVEL')
        return False
Exemple #5
0
    def set_title(bot, source, message, event, args):
        # XXX: This should be a module
        if message:
            bot.twitchapi.set_title(bot.streamer, message)
            log_msg = '{0} updated the title to "{1}"'.format(source.username_raw, message)
            bot.say(log_msg)

            AdminLogManager.add_entry("Title set", source, log_msg)
Exemple #6
0
    def add_command(bot, source, message, event, args):
        """Dispatch method for creating commands.
        Usage: !add command ALIAS [options] RESPONSE
        Multiple options available:
        --whisper/--no-whisper
        --reply/--no-reply
        --modonly/--no-modonly
        --cd CD
        --usercd USERCD
        --level LEVEL
        --cost COST
        """

        if message:
            # Make sure we got both an alias and a response
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source.username, "Usage: !add command ALIAS [options] RESPONSE")
                return False

            options, response = bot.commands.parse_command_arguments(message_parts[1:])

            options["added_by"] = source.id

            if options is False:
                bot.whisper(source.username, "Invalid command")
                return False

            alias_str = message_parts[0].replace("!", "").lower()
            type = "say"
            if options["whisper"] is True:
                type = "whisper"
            elif options["reply"] is True:
                type = "reply"
            elif response.startswith("/me") or response.startswith(".me"):
                type = "me"
                response = " ".join(response.split(" ")[1:])
            elif options["whisper"] is False or options["reply"] is False:
                type = "say"
            action = {"type": type, "message": response}

            command, new_command, alias_matched = bot.commands.create_command(alias_str, action=action, **options)
            if new_command is True:
                bot.whisper(source.username, "Added your command (ID: {command.id})".format(command=command))

                log_msg = "The !{} command has been created".format(command.command.split("|")[0])
                AdminLogManager.add_entry("Command created", source, log_msg)
                return True

            # At least one alias is already in use, notify the user to use !edit command instead
            bot.whisper(
                source.username,
                "The alias {} is already in use. To edit that command, use !edit command instead of !add command.".format(
                    alias_matched
                ),
            )
            return False
Exemple #7
0
    def add_command(bot, source, message, event, args):
        """Dispatch method for creating commands.
        Usage: !add command ALIAS [options] RESPONSE
        Multiple options available:
        --whisper/--no-whisper
        --reply/--no-reply
        --modonly/--no-modonly
        --cd CD
        --usercd USERCD
        --level LEVEL
        --cost COST
        """

        if message:
            # Make sure we got both an alias and a response
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source.username, 'Usage: !add command ALIAS [options] RESPONSE')
                return False

            options, response = bot.commands.parse_command_arguments(message_parts[1:])

            options['added_by'] = source.id

            if options is False:
                bot.whisper(source.username, 'Invalid command')
                return False

            alias_str = message_parts[0].replace('!', '').lower()
            type = 'say'
            if options['whisper'] is True:
                type = 'whisper'
            elif options['reply'] is True:
                type = 'reply'
            elif response.startswith('/me') or response.startswith('.me'):
                type = 'me'
                response = ' '.join(response.split(' ')[1:])
            elif options['whisper'] is False or options['reply'] is False:
                type = 'say'
            action = {
                'type': type,
                'message': response,
            }

            command, new_command, alias_matched = bot.commands.create_command(alias_str, action=action, **options)
            if new_command is True:
                bot.whisper(source.username, 'Added your command (ID: {command.id})'.format(command=command))

                log_msg = 'The !{} command has been created'.format(command.command.split('|')[0])
                AdminLogManager.add_entry('Command created',
                        source,
                        log_msg)
                return True

            # At least one alias is already in use, notify the user to use !edit command instead
            bot.whisper(source.username, 'The alias {} is already in use. To edit that command, use !edit command instead of !add command.'.format(alias_matched))
            return False
Exemple #8
0
    def set_title(bot, source, message, event, args):
        # XXX: This should be a module
        if message:
            bot.twitchapi.set_title(bot.streamer, message)
            log_msg = '{0} updated the title to "{1}"'.format(
                source.username_raw, message)
            bot.say(log_msg)

            AdminLogManager.add_entry('Title set', source, log_msg)
Exemple #9
0
    def add_alias(bot, source, message, event, args):
        """Dispatch method for adding aliases to already-existing commands.
        Usage: !add alias EXISTING_ALIAS NEW_ALIAS_1 NEW_ALIAS_2 ...
        """

        if message:
            message = message.replace('!', '').lower()
            # Make sure we got both an existing alias and at least one new alias
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source.username,
                            'Usage: !add alias existingalias newalias')
                return False

            existing_alias = message_parts[0]
            new_aliases = re.split('\|| ', ' '.join(message_parts[1:]))
            added_aliases = []
            already_used_aliases = []

            if existing_alias not in bot.commands:
                bot.whisper(
                    source.username,
                    'No command called "{0}" found'.format(existing_alias))
                return False

            command = bot.commands[existing_alias]

            for alias in set(new_aliases):
                if alias in bot.commands:
                    already_used_aliases.append(alias)
                else:
                    added_aliases.append(alias)
                    bot.commands[alias] = command

            if len(added_aliases) > 0:
                new_aliases = '{}|{}'.format(command.command,
                                             '|'.join(added_aliases))
                bot.commands.edit_command(command, command=new_aliases)

                bot.whisper(
                    source.username,
                    'Successfully added the aliases {0} to {1}'.format(
                        ', '.join(added_aliases), existing_alias))
                log_msg = 'The aliases {0} has been added to {1}'.format(
                    ', '.join(added_aliases), existing_alias)
                AdminLogManager.add_entry('Alias added', source, log_msg)
            if len(already_used_aliases) > 0:
                bot.whisper(
                    source.username,
                    'The following aliases were already in use: {0}'.format(
                        ', '.join(already_used_aliases)))
        else:
            bot.whisper(source.username,
                        'Usage: !add alias existingalias newalias')
Exemple #10
0
    def remove_alias(bot, source, message, event, args):
        """Dispatch method for removing aliases from a command.
        Usage: !remove alias EXISTING_ALIAS_1 EXISTING_ALIAS_2"""
        if message:
            aliases = re.split('\|| ', message.lower())
            log.info(aliases)
            if len(aliases) < 1:
                bot.whisper(source.username,
                            'Usage: !remove alias EXISTINGALIAS')
                return False

            num_removed = 0
            commands_not_found = []
            for alias in aliases:
                if alias not in bot.commands:
                    commands_not_found.append(alias)
                    continue

                command = bot.commands[alias]

                current_aliases = command.command.split('|')
                current_aliases.remove(alias)

                if len(current_aliases) == 0:
                    bot.whisper(
                        source.username,
                        "{0} is the only remaining alias for this command and can't be removed."
                        .format(alias))
                    continue

                new_aliases = '|'.join(current_aliases)
                bot.commands.edit_command(command, command=new_aliases)

                num_removed += 1
                del bot.commands[alias]
                log_msg = 'The alias {0} has been removed from {1}'.format(
                    alias,
                    new_aliases.split('|')[0])
                AdminLogManager.add_entry('Alias removed', source, log_msg)

            whisper_str = ''
            if num_removed > 0:
                whisper_str = 'Successfully removed {0} aliases.'.format(
                    num_removed)
            if len(commands_not_found) > 0:
                whisper_str += ' Aliases {0} not found'.format(
                    ', '.join(commands_not_found))
            if len(whisper_str) > 0:
                bot.whisper(source.username, whisper_str)
        else:
            bot.whisper(source.username, 'Usage: !remove alias EXISTINGALIAS')
Exemple #11
0
    def remove_command(bot, source, message, event, args):
        if message:
            id = None
            command = None
            try:
                id = int(message)
            except Exception:
                pass

            if id is None:
                potential_cmd = ''.join(
                    message.split(' ')[:1]).lower().replace('!', '')
                if potential_cmd in bot.commands:
                    command = bot.commands[potential_cmd]
                    log.info('got command: {0}'.format(command))
            else:
                for key, check_command in bot.commands.items():
                    if check_command.id == id:
                        command = check_command
                        break

            if command is None:
                bot.whisper(source.username,
                            'No command with the given parameters found')
                return False

            if command.id == -1:
                bot.whisper(
                    source.username,
                    'That command is an internal command, it cannot be removed.'
                )
                return False

            if source.level < 2000:
                if command.action is not None and not command.action.type == 'message':
                    bot.whisper(
                        source.username,
                        'That command is not a normal command, it cannot be removed by you.'
                    )
                    return False

            bot.whisper(
                source.username,
                'Successfully removed command with id {0}'.format(command.id))
            log_msg = 'The !{} command has been removed'.format(
                command.command.split('|')[0])
            AdminLogManager.add_entry('Command removed', source, log_msg)
            bot.commands.remove_command(command)
        else:
            bot.whisper(source.username,
                        'Usage: !remove command (COMMAND_ID|COMMAND_ALIAS)')
Exemple #12
0
    def add_alias(bot, source, message, event, args):
        """Dispatch method for adding aliases to already-existing commands.
        Usage: !add alias EXISTING_ALIAS NEW_ALIAS_1 NEW_ALIAS_2 ...
        """

        if message:
            message = message.replace("!", "").lower()
            # Make sure we got both an existing alias and at least one new alias
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source.username, "Usage: !add alias existingalias newalias")
                return False

            existing_alias = message_parts[0]
            new_aliases = re.split("\|| ", " ".join(message_parts[1:]))
            added_aliases = []
            already_used_aliases = []

            if existing_alias not in bot.commands:
                bot.whisper(source.username, 'No command called "{0}" found'.format(existing_alias))
                return False

            command = bot.commands[existing_alias]

            for alias in set(new_aliases):
                if alias in bot.commands:
                    already_used_aliases.append(alias)
                else:
                    added_aliases.append(alias)
                    bot.commands[alias] = command

            if len(added_aliases) > 0:
                new_aliases = "{}|{}".format(command.command, "|".join(added_aliases))
                bot.commands.edit_command(command, command=new_aliases)

                bot.whisper(
                    source.username,
                    "Successfully added the aliases {0} to {1}".format(", ".join(added_aliases), existing_alias),
                )
                log_msg = "The aliases {0} has been added to {1}".format(", ".join(added_aliases), existing_alias)
                AdminLogManager.add_entry("Alias added", source, log_msg)
            if len(already_used_aliases) > 0:
                bot.whisper(
                    source.username,
                    "The following aliases were already in use: {0}".format(", ".join(already_used_aliases)),
                )
        else:
            bot.whisper(source.username, "Usage: !add alias existingalias newalias")
Exemple #13
0
    def permaban(bot, source, message, event, args):
        if message:
            msg_args = message.split(' ')
            username = msg_args[0].lower()
            user = bot.users[username]

            if user.banned:
                bot.whisper(source.username, 'User is already permabanned.')
                return False

            user.banned = True
            message = message.lower()
            log_msg = '{} has been permabanned'.format(user.username_raw)
            bot.whisper(source.username, log_msg)

            AdminLogManager.add_entry('Permaban added', source, log_msg)
Exemple #14
0
    def remove_alias(bot, source, message, event, args):
        """Dispatch method for removing aliases from a command.
        Usage: !remove alias EXISTING_ALIAS_1 EXISTING_ALIAS_2"""
        if message:
            aliases = re.split("\|| ", message.lower())
            log.info(aliases)
            if len(aliases) < 1:
                bot.whisper(source.username, "Usage: !remove alias EXISTINGALIAS")
                return False

            num_removed = 0
            commands_not_found = []
            for alias in aliases:
                if alias not in bot.commands:
                    commands_not_found.append(alias)
                    continue

                command = bot.commands[alias]

                current_aliases = command.command.split("|")
                current_aliases.remove(alias)

                if len(current_aliases) == 0:
                    bot.whisper(
                        source.username,
                        "{0} is the only remaining alias for this command and can't be removed.".format(alias),
                    )
                    continue

                new_aliases = "|".join(current_aliases)
                bot.commands.edit_command(command, command=new_aliases)

                num_removed += 1
                del bot.commands[alias]
                log_msg = "The alias {0} has been removed from {1}".format(alias, new_aliases.split("|")[0])
                AdminLogManager.add_entry("Alias removed", source, log_msg)

            whisper_str = ""
            if num_removed > 0:
                whisper_str = "Successfully removed {0} aliases.".format(num_removed)
            if len(commands_not_found) > 0:
                whisper_str += " Aliases {0} not found".format(", ".join(commands_not_found))
            if len(whisper_str) > 0:
                bot.whisper(source.username, whisper_str)
        else:
            bot.whisper(source.username, "Usage: !remove alias EXISTINGALIAS")
Exemple #15
0
    def get(self, command_id, **options):
        with DBManager.create_session_scope() as db_session:
            command = db_session.query(Command).filter_by(id=command_id).one_or_none()
            if command is None:
                return {'error': 'Invalid command ID'}, 404
            if command.level > options['user'].level:
                return {'error': 'Unauthorized'}, 403
            log_msg = 'The !{} command has been removed'.format(command.command.split('|')[0])
            AdminLogManager.add_entry('Command removed',
                    options['user'],
                    log_msg)
            db_session.delete(command.data)
            db_session.delete(command)

        if SocketClientManager.send('command.remove', {'command_id': command_id}) is True:
            return {'success': 'good job'}, 200
        else:
            return {'error': 'could not push update'}, 500
Exemple #16
0
    def unpermaban(bot, source, message, event, args):
        if message:
            tmp_username = message.split(' ')[0].strip().lower()
            user = bot.users.find(tmp_username)

            if not user:
                bot.whisper(source.username, 'No user with that name found.')
                return False

            if user.banned is False:
                bot.whisper(source.username, 'User is not permabanned.')
                return False

            user.banned = False
            message = message.lower()
            log_msg = '{} is no longer permabanned'.format(user.username_raw)
            bot.whisper(source.username, log_msg)

            AdminLogManager.add_entry('Permaban remove', source, log_msg)
Exemple #17
0
    def permaban_command(self, **options):
        message = options['message']
        bot = options['bot']
        source = options['source']

        if message:
            msg_args = message.split(' ')
            username = msg_args[0].lower()
            user = bot.users[username]

            if user.banned:
                bot.whisper(source.username, 'User is already permabanned.')
                return False

            user.banned = True
            message = message.lower()
            log_msg = '{} has been permabanned'.format(user.username_raw)
            bot.whisper(source.username, log_msg)

            AdminLogManager.add_entry('Permaban added', source, log_msg)
Exemple #18
0
    def remove_command(bot, source, message, event, args):
        if message:
            id = None
            command = None
            try:
                id = int(message)
            except Exception:
                pass

            if id is None:
                potential_cmd = ''.join(message.split(' ')[:1]).lower().replace('!', '')
                if potential_cmd in bot.commands:
                    command = bot.commands[potential_cmd]
                    log.info('got command: {0}'.format(command))
            else:
                for key, check_command in bot.commands.items():
                    if check_command.id == id:
                        command = check_command
                        break

            if command is None:
                bot.whisper(source.username, 'No command with the given parameters found')
                return False

            if command.id == -1:
                bot.whisper(source.username, 'That command is an internal command, it cannot be removed.')
                return False

            if source.level < 2000:
                if command.action is not None and not command.action.type == 'message':
                    bot.whisper(source.username, 'That command is not a normal command, it cannot be removed by you.')
                    return False

            bot.whisper(source.username, 'Successfully removed command with id {0}'.format(command.id))
            log_msg = 'The !{} command has been removed'.format(command.command.split('|')[0])
            AdminLogManager.add_entry('Command removed',
                    source,
                    log_msg)
            bot.commands.remove_command(command)
        else:
            bot.whisper(source.username, 'Usage: !remove command (COMMAND_ID|COMMAND_ALIAS)')
Exemple #19
0
    def unpermaban_command(self, **options):
        message = options['message']
        bot = options['bot']
        source = options['source']

        if message:
            tmp_username = message.split(' ')[0].strip().lower()
            user = bot.users.find(tmp_username)

            if not user:
                bot.whisper(source.username, 'No user with that name found.')
                return False

            if user.banned is False:
                bot.whisper(source.username, 'User is not permabanned.')
                return False

            user.banned = False
            message = message.lower()
            log_msg = '{} is no longer permabanned'.format(user.username_raw)
            bot.whisper(source.username, log_msg)

            AdminLogManager.add_entry('Permaban remove', source, log_msg)
Exemple #20
0
def command_remove(command_id, **options):
    with DBManager.create_session_scope() as db_session:
        command = db_session.query(Command).filter_by(
            id=command_id).one_or_none()
        if command is None:
            return make_response(jsonify({'error': 'Invalid command ID'}), 404)
        if command.level > options['user'].level:
            abort(403)
        log_msg = 'The !{} command has been removed'.format(
            command.command.split('|')[0])
        AdminLogManager.add_entry('Command removed', options['user'], log_msg)
        db_session.delete(command.data)
        db_session.delete(command)

    payload = {'event': 'command.remove', 'data': {'command_id': command_id}}
    payload_bytes = json.dumps(payload).encode('utf-8')
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
            client.connect(config['sock']['sock_file'])
            client.sendall(payload_bytes)
            return make_response(jsonify({'success': 'good job'}))
    except:
        log.exception('???')
        return make_response(jsonify({'error': 'Could not push update'}))
Exemple #21
0
    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)

            user = options.get('user', None)

            if user is None:
                abort(403)

            options = {
                'delay_all': delay_all,
                'delay_user': delay_user,
                'level': level,
                'cost': cost,
                'added_by': user.id,
            }

            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, **options)
            log_msg = 'The !{} command has been created'.format(command.command.split('|')[0])
            AdminLogManager.add_entry('Command created',
                    user,
                    log_msg)
            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')
Exemple #22
0
def command_update(command_id, **extra_args):
    if not request.method == 'POST':
        return make_response(
            jsonify({'error': 'Invalid request method. (Expected POST)'}), 400)
    if len(request.form) == 0:
        return make_response(jsonify({'error': 'Missing parameter to edit.'}),
                             400)

    valid_names = [
        'enabled', 'level', 'delay_all', 'delay_user', 'cost',
        'can_execute_with_whisper', 'sub_only'
    ]

    valid_action_names = ['type', 'message']

    with DBManager.create_session_scope() as db_session:
        command = db_session.query(Command).options(
            joinedload(Command.data).joinedload(
                CommandData.user)).filter_by(id=command_id).one_or_none()
        if command is None:
            return make_response(jsonify({'error': 'Invalid command ID'}), 404)
        if command.level > extra_args['user'].level:
            abort(403)
        parsed_action = json.loads(command.action_json)
        options = {
            'edited_by': extra_args['user'].id,
        }

        for key in request.form:
            if key.startswith('data_'):
                name = key[5:]
                value = request.form[key]

                if name.startswith('action_'):
                    name = name[7:]
                    if name in valid_action_names and name in parsed_action and command.action.type == 'message':
                        value_type = type(parsed_action[name])
                        if value_type is bool:
                            parsed_value = True if value == '1' else False
                        elif value_type is int:
                            try:
                                parsed_value = int(value)
                            except ValueError:
                                continue
                        else:
                            parsed_value = value
                        parsed_action[name] = parsed_value
                    command.action_json = json.dumps(parsed_action)
                else:
                    if name in valid_names:
                        value_type = type(getattr(command, name))
                        if value_type is bool:
                            parsed_value = True if value == '1' else False
                        elif value_type is int:
                            try:
                                parsed_value = int(value)
                            except ValueError:
                                continue
                        else:
                            parsed_value = value
                        options[name] = parsed_value

        aj = json.loads(command.action_json)
        old_message = ''
        new_message = ''
        try:
            old_message = command.action.response
            new_message = aj['message']
        except:
            pass

        command.set(**options)
        command.data.set(**options)

        if len(old_message) > 0 and old_message != new_message:
            log_msg = 'The !{} command has been updated from "{}" to "{}"'.format(
                command.command.split('|')[0], old_message, new_message)
        else:
            log_msg = 'The !{} command has been updated'.format(
                command.command.split('|')[0])

        AdminLogManager.add_entry('Command edited',
                                  extra_args['user'],
                                  log_msg,
                                  data={
                                      'old_message': old_message,
                                      'new_message': new_message,
                                  })

    if SocketClientManager.send('command.update',
                                {'command_id': command_id}) is True:
        return make_response(jsonify({'success': 'good job'}))
    else:
        return make_response(jsonify({'error': 'Could not push update'}))
Exemple #23
0
    def timers_create(**options):
        session.pop('timer_created_id', None)
        session.pop('timer_edited_id', None)
        if request.method == 'POST':
            id = None
            try:
                if 'id' in request.form:
                    id = int(request.form['id'])
                name = request.form['name'].strip()
                interval_online = int(request.form['interval_online'])
                interval_offline = int(request.form['interval_offline'])
                message_type = request.form['message_type']
                message = request.form['message'].strip()
            except (KeyError, ValueError):
                abort(403)

            if interval_online < 0 or interval_offline < 0:
                abort(403)

            if message_type not in ['say', 'me']:
                abort(403)

            if len(message) == 0:
                abort(403)

            user = options.get('user', None)

            if user is None:
                abort(403)

            options = {
                    'name': name,
                    'interval_online': interval_online,
                    'interval_offline': interval_offline,
                    }

            action = {
                    'type': message_type,
                    'message': message
                    }
            options['action'] = action

            if id is None:
                timer = Timer(**options)

            with DBManager.create_session_scope(expire_on_commit=False) as db_session:
                if id is not None:
                    timer = db_session.query(Timer).filter_by(id=id).one_or_none()
                    if timer is None:
                        return redirect('/admin/timers/', 303)

                    old_message = ''
                    new_message = ''
                    try:
                        old_message = timer.action.response
                        new_message = action['message']
                    except:
                        pass

                    timer.set(**options)

                    if len(old_message) > 0 and old_message != new_message:
                        log_msg = 'Timer "{0}" has been updated from "{1}" to "{2}"'.format(
                                timer.name,
                                old_message,
                                new_message)
                    else:
                        log_msg = 'Timer "{0}" has been updated'.format(timer.name)

                    AdminLogManager.add_entry('Timer edited',
                            user,
                            log_msg,
                            data={
                                'old_message': old_message,
                                'new_message': new_message,
                                })
                else:
                    db_session.add(timer)
                    AdminLogManager.post('Timer added', user, timer.name)

            SocketClientManager.send('timer.update', {'timer_id': timer.id})
            if id is None:
                session['timer_created_id'] = timer.id
            else:
                session['timer_edited_id'] = timer.id
            return redirect('/admin/timers/', 303)
        else:
            return render_template('admin/create_timer.html')
Exemple #24
0
def command_update(command_id, **extra_args):
    if not request.method == 'POST':
        return make_response(jsonify({'error': 'Invalid request method. (Expected POST)'}), 400)
    if len(request.form) == 0:
        return make_response(jsonify({'error': 'Missing parameter to edit.'}), 400)

    valid_names = [
            'enabled',
            'level',
            'delay_all',
            'delay_user',
            'cost',
            'can_execute_with_whisper',
            'sub_only'
            ]

    valid_action_names = [
            'type',
            'message'
            ]

    with DBManager.create_session_scope() as db_session:
        command = db_session.query(Command).options(joinedload(Command.data).joinedload(CommandData.user)).filter_by(id=command_id).one_or_none()
        if command is None:
            return make_response(jsonify({'error': 'Invalid command ID'}), 404)
        if command.level > extra_args['user'].level:
            abort(403)
        parsed_action = json.loads(command.action_json)
        options = {
            'edited_by': extra_args['user'].id,
        }

        for key in request.form:
            if key.startswith('data_'):
                name = key[5:]
                value = request.form[key]

                if name.startswith('action_'):
                    name = name[7:]
                    if name in valid_action_names and name in parsed_action and command.action.type == 'message':
                        value_type = type(parsed_action[name])
                        if value_type is bool:
                            parsed_value = True if value == '1' else False
                        elif value_type is int:
                            try:
                                parsed_value = int(value)
                            except ValueError:
                                continue
                        else:
                            parsed_value = value
                        parsed_action[name] = parsed_value
                    command.action_json = json.dumps(parsed_action)
                else:
                    if name in valid_names:
                        value_type = type(getattr(command, name))
                        if value_type is bool:
                            parsed_value = True if value == '1' else False
                        elif value_type is int:
                            try:
                                parsed_value = int(value)
                            except ValueError:
                                continue
                        else:
                            parsed_value = value
                        options[name] = parsed_value

        aj = json.loads(command.action_json)
        old_message = ''
        new_message = ''
        try:
            old_message = command.action.response
            new_message = aj['message']
        except:
            pass

        command.set(**options)
        command.data.set(**options)

        if len(old_message) > 0 and old_message != new_message:
            log_msg = 'The !{} command has been updated from "{}" to "{}"'.format(
                    command.command.split('|')[0],
                    old_message,
                    new_message)
        else:
            log_msg = 'The !{} command has been updated'.format(command.command.split('|')[0])

        AdminLogManager.add_entry('Command edited',
                extra_args['user'],
                log_msg,
                data={
                    'old_message': old_message,
                    'new_message': new_message,
                    })

    if SocketClientManager.send('command.update', {'command_id': command_id}) is True:
        return make_response(jsonify({'success': 'good job'}))
    else:
        return make_response(jsonify({'error': 'Could not push update'}))
Exemple #25
0
    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)

            user = options.get('user', None)

            if user is None:
                abort(403)

            options = {
                'delay_all': delay_all,
                'delay_user': delay_user,
                'level': level,
                'cost': cost,
                'added_by': user.id,
            }

            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, **options)
            log_msg = 'The !{} command has been created'.format(
                command.command.split('|')[0])
            AdminLogManager.add_entry('Command created', user, log_msg)
            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')
Exemple #26
0
    def edit_command(bot, source, message, event, args):
        """Dispatch method for editing commands.
        Usage: !edit command ALIAS [options] RESPONSE
        Multiple options available:
        --whisper/--no-whisper
        --reply/--no-reply
        --modonly/--no-modonly
        --cd CD
        --usercd USERCD
        --level LEVEL
        --cost COST
        """

        if message:
            # Make sure we got both an alias and a response
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source.username,
                            'Usage: !add command ALIAS [options] RESPONSE')
                return False

            options, response = bot.commands.parse_command_arguments(
                message_parts[1:])

            options['edited_by'] = source.id

            if options is False:
                bot.whisper(source.username, 'Invalid command')
                return False

            alias = message_parts[0].replace('!', '').lower()
            type = 'say'
            if options['whisper'] is True:
                type = 'whisper'
            elif options['reply'] is True:
                type = 'reply'
            elif response.startswith('/me') or response.startswith('.me'):
                type = 'me'
                response = ' '.join(response.split(' ')[1:])
            elif options['whisper'] is False or options['reply'] is False:
                type = 'say'
            action = {
                'type': type,
                'message': response,
            }

            command = bot.commands.get(alias, None)

            if command is None:
                bot.whisper(
                    source.username,
                    'No command found with the alias {}. Did you mean to create the command? If so, use !add command instead.'
                    .format(alias))
                return False

            old_message = ''
            new_message = ''

            if len(action['message']) > 0:
                options['action'] = action
                old_message = command.action.response
                new_message = action['message']
            elif not type == command.action.subtype:
                options['action'] = {
                    'type': type,
                    'message': command.action.response,
                }
            bot.commands.edit_command(command, **options)
            bot.whisper(
                source.username,
                'Updated the command (ID: {command.id})'.format(
                    command=command))

            if len(new_message) > 0:
                log_msg = 'The !{} command has been updated from "{}" to "{}"'.format(
                    command.command.split('|')[0], old_message, new_message)
            else:
                log_msg = 'The !{} command has been updated'.format(
                    command.command.split('|')[0])

            AdminLogManager.add_entry('Command edited',
                                      source,
                                      log_msg,
                                      data={
                                          'old_message': old_message,
                                          'new_message': new_message,
                                      })
Exemple #27
0
    def add_command(bot, source, message, event, args):
        """Dispatch method for creating commands.
        Usage: !add command ALIAS [options] RESPONSE
        Multiple options available:
        --whisper/--no-whisper
        --reply/--no-reply
        --modonly/--no-modonly
        --cd CD
        --usercd USERCD
        --level LEVEL
        --cost COST
        """

        if message:
            # Make sure we got both an alias and a response
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source.username,
                            'Usage: !add command ALIAS [options] RESPONSE')
                return False

            options, response = bot.commands.parse_command_arguments(
                message_parts[1:])

            options['added_by'] = source.id

            if options is False:
                bot.whisper(source.username, 'Invalid command')
                return False

            alias_str = message_parts[0].replace('!', '').lower()
            type = 'say'
            if options['whisper'] is True:
                type = 'whisper'
            elif options['reply'] is True:
                type = 'reply'
            elif response.startswith('/me') or response.startswith('.me'):
                type = 'me'
                response = ' '.join(response.split(' ')[1:])
            elif options['whisper'] is False or options['reply'] is False:
                type = 'say'
            action = {
                'type': type,
                'message': response,
            }

            command, new_command, alias_matched = bot.commands.create_command(
                alias_str, action=action, **options)
            if new_command is True:
                bot.whisper(
                    source.username,
                    'Added your command (ID: {command.id})'.format(
                        command=command))

                log_msg = 'The !{} command has been created'.format(
                    command.command.split('|')[0])
                AdminLogManager.add_entry('Command created', source, log_msg)
                return True

            # At least one alias is already in use, notify the user to use !edit command instead
            bot.whisper(
                source.username,
                'The alias {} is already in use. To edit that command, use !edit command instead of !add command.'
                .format(alias_matched))
            return False
Exemple #28
0
    def timers_create(**options):
        session.pop('timer_created_id', None)
        session.pop('timer_edited_id', None)
        if request.method == 'POST':
            id = None
            try:
                if 'id' in request.form:
                    id = int(request.form['id'])
                name = request.form['name'].strip()
                interval_online = int(request.form['interval_online'])
                interval_offline = int(request.form['interval_offline'])
                message_type = request.form['message_type']
                message = request.form['message'].strip()
            except (KeyError, ValueError):
                abort(403)

            if interval_online < 0 or interval_offline < 0:
                abort(403)

            if message_type not in ['say', 'me']:
                abort(403)

            if len(message) == 0:
                abort(403)

            user = options.get('user', None)

            if user is None:
                abort(403)

            options = {
                'name': name,
                'interval_online': interval_online,
                'interval_offline': interval_offline,
            }

            action = {'type': message_type, 'message': message}
            options['action'] = action

            if id is None:
                timer = Timer(**options)

            with DBManager.create_session_scope(
                    expire_on_commit=False) as db_session:
                if id is not None:
                    timer = db_session.query(Timer).filter_by(
                        id=id).one_or_none()
                    if timer is None:
                        return redirect('/admin/timers/', 303)

                    old_message = ''
                    new_message = ''
                    try:
                        old_message = timer.action.response
                        new_message = action['message']
                    except:
                        pass

                    timer.set(**options)

                    if len(old_message) > 0 and old_message != new_message:
                        log_msg = 'Timer "{0}" has been updated from "{1}" to "{2}"'.format(
                            timer.name, old_message, new_message)
                    else:
                        log_msg = 'Timer "{0}" has been updated'.format(
                            timer.name)

                    AdminLogManager.add_entry('Timer edited',
                                              user,
                                              log_msg,
                                              data={
                                                  'old_message': old_message,
                                                  'new_message': new_message,
                                              })
                else:
                    db_session.add(timer)
                    AdminLogManager.post('Timer added', user, timer.name)

            SocketClientManager.send('timer.update', {'timer_id': timer.id})
            if id is None:
                session['timer_created_id'] = timer.id
            else:
                session['timer_edited_id'] = timer.id
            return redirect('/admin/timers/', 303)
        else:
            return render_template('admin/create_timer.html')
Exemple #29
0
    def edit_command(bot, source, message, event, args):
        """Dispatch method for editing commands.
        Usage: !edit command ALIAS [options] RESPONSE
        Multiple options available:
        --whisper/--no-whisper
        --reply/--no-reply
        --modonly/--no-modonly
        --cd CD
        --usercd USERCD
        --level LEVEL
        --cost COST
        """

        if message:
            # Make sure we got both an alias and a response
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source.username, "Usage: !add command ALIAS [options] RESPONSE")
                return False

            options, response = bot.commands.parse_command_arguments(message_parts[1:])

            options["edited_by"] = source.id

            if options is False:
                bot.whisper(source.username, "Invalid command")
                return False

            alias = message_parts[0].replace("!", "").lower()
            type = "say"
            if options["whisper"] is True:
                type = "whisper"
            elif options["reply"] is True:
                type = "reply"
            elif response.startswith("/me") or response.startswith(".me"):
                type = "me"
                response = " ".join(response.split(" ")[1:])
            elif options["whisper"] is False or options["reply"] is False:
                type = "say"
            action = {"type": type, "message": response}

            command = bot.commands.get(alias, None)

            if command is None:
                bot.whisper(
                    source.username,
                    "No command found with the alias {}. Did you mean to create the command? If so, use !add command instead.".format(
                        alias
                    ),
                )
                return False

            old_message = ""
            new_message = ""

            if len(action["message"]) > 0:
                options["action"] = action
                old_message = command.action.response
                new_message = action["message"]
            elif not type == command.action.subtype:
                options["action"] = {"type": type, "message": command.action.response}
            bot.commands.edit_command(command, **options)
            bot.whisper(source.username, "Updated the command (ID: {command.id})".format(command=command))

            if len(new_message) > 0:
                log_msg = 'The !{} command has been updated from "{}" to "{}"'.format(
                    command.command.split("|")[0], old_message, new_message
                )
            else:
                log_msg = "The !{} command has been updated".format(command.command.split("|")[0])

            AdminLogManager.add_entry(
                "Command edited", source, log_msg, data={"old_message": old_message, "new_message": new_message}
            )
Exemple #30
0
    def edit_command(bot, source, message, event, args):
        """Dispatch method for editing commands.
        Usage: !edit command ALIAS [options] RESPONSE
        Multiple options available:
        --whisper/--no-whisper
        --reply/--no-reply
        --modonly/--no-modonly
        --cd CD
        --usercd USERCD
        --level LEVEL
        --cost COST
        """

        if message:
            # Make sure we got both an alias and a response
            message_parts = message.split()
            if len(message_parts) < 2:
                bot.whisper(source.username, 'Usage: !add command ALIAS [options] RESPONSE')
                return False

            options, response = bot.commands.parse_command_arguments(message_parts[1:])

            options['edited_by'] = source.id

            if options is False:
                bot.whisper(source.username, 'Invalid command')
                return False

            alias = message_parts[0].replace('!', '').lower()
            type = 'say'
            if options['whisper'] is True:
                type = 'whisper'
            elif options['reply'] is True:
                type = 'reply'
            elif response.startswith('/me') or response.startswith('.me'):
                type = 'me'
                response = ' '.join(response.split(' ')[1:])
            elif options['whisper'] is False or options['reply'] is False:
                type = 'say'
            action = {
                'type': type,
                'message': response,
            }

            command = bot.commands.get(alias, None)

            if command is None:
                bot.whisper(source.username, 'No command found with the alias {}. Did you mean to create the command? If so, use !add command instead.'.format(alias))
                return False

            old_message = ''
            new_message = ''

            if len(action['message']) > 0:
                options['action'] = action
                old_message = command.action.response
                new_message = action['message']
            elif not type == command.action.subtype:
                options['action'] = {
                    'type': type,
                    'message': command.action.response,
                }
            bot.commands.edit_command(command, **options)
            bot.whisper(source.username, 'Updated the command (ID: {command.id})'.format(command=command))

            if len(new_message) > 0:
                log_msg = 'The !{} command has been updated from "{}" to "{}"'.format(
                        command.command.split('|')[0],
                        old_message,
                        new_message)
            else:
                log_msg = 'The !{} command has been updated'.format(command.command.split('|')[0])

            AdminLogManager.add_entry('Command edited',
                    source,
                    log_msg,
                    data={
                        'old_message': old_message,
                        'new_message': new_message,
                        })