当前位置: 首页>>代码示例>>Python>>正文


Python sock.SocketClientManager类代码示例

本文整理汇总了Python中pajbot.models.sock.SocketClientManager的典型用法代码示例。如果您正苦于以下问题:Python SocketClientManager类的具体用法?Python SocketClientManager怎么用?Python SocketClientManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了SocketClientManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: modules_edit

    def modules_edit(module_id, **options):
        module_manager = ModuleManager(None).load(do_reload=False)
        current_module = find(lambda m: m.ID == module_id, module_manager.all_modules)

        if current_module is None:
            return render_template('admin/module_404.html'), 404

        sub_modules = []
        for module in module_manager.all_modules:
            module.db_module = None

        with DBManager.create_session_scope() as db_session:
            for db_module in db_session.query(Module):
                module = find(lambda m: m.ID == db_module.id, module_manager.all_modules)
                if module:
                    module.db_module = db_module
                    if module.PARENT_MODULE == current_module.__class__:
                        sub_modules.append(module)

            if current_module.db_module is None:
                return render_template('admin/module_404.html'), 404

            if request.method == 'POST':
                form_values = {key: value for key, value in request.form.items()}
                res = current_module.parse_settings(**form_values)
                if res is False:
                    return render_template('admin/module_404.html'), 404

                current_module.db_module.settings = json.dumps(res)
                db_session.commit()

                settings = None
                try:
                    settings = json.loads(current_module.db_module.settings)
                except (TypeError, ValueError):
                    pass
                current_module.load(settings=settings)

                payload = {
                        'id': current_module.db_module.id,
                        }

                SocketClientManager.send('module.update', payload)

                AdminLogManager.post('Module edited', options['user'], current_module.NAME)

                return render_template('admin/configure_module.html',
                        module=current_module,
                        sub_modules=sub_modules)
            else:
                settings = None
                try:
                    settings = json.loads(current_module.db_module.settings)
                except (TypeError, ValueError):
                    pass
                current_module.load(settings=settings)

                return render_template('admin/configure_module.html',
                        module=current_module,
                        sub_modules=sub_modules)
开发者ID:Nacht123,项目名称:pajbot,代码行数:60,代码来源:modules.py

示例2: generic_toggle

def generic_toggle(route_key, row_id, **options):
    valid_routes = {
            'timer': Timer,
            'banphrase': Banphrase,
            'module': Module,
            }

    if route_key not in valid_routes:
        return make_response(jsonify({'error': 'Invalid route.'}), 400)
    if 'new_state' not in request.form:
        return make_response(jsonify({'error': 'Missing `new_state` parameter.'}), 400)
    try:
        new_state = int(request.form['new_state'])
    except (ValueError, KeyError):
        return make_response(jsonify({'error': 'Invalid `new_state` parameter.'}), 400)

    route_value = valid_routes[route_key]

    with DBManager.create_session_scope() as db_session:
        row = db_session.query(route_value).filter_by(id=row_id).one_or_none()
        if row:
            row.enabled = True if new_state == 1 else False
            db_session.commit()
            SocketClientManager.send('{}.update'.format(route_key), {'{}_id'.format(route_key): row.id})
            return make_response(jsonify({'success': 'successful toggle', 'new_state': new_state}))
        else:
            return make_response(jsonify({'error': 'invalid {} id'.format(route_key)}))
开发者ID:gigglearrows,项目名称:pajbot,代码行数:27,代码来源:api.py

示例3: post

    def post(self, row_id, **options):
        args = self.post_parser.parse_args()

        try:
            new_state = int(args['new_state'])
        except (ValueError, KeyError):
            return {'error': 'Invalid `new_state` parameter.'}, 400

        with DBManager.create_session_scope() as db_session:
            row = db_session.query(Banphrase).filter_by(id=row_id).one_or_none()

            if not row:
                return {
                        'error': 'Banphrase with this ID not found'
                        }, 404

            row.enabled = True if new_state == 1 else False
            db_session.commit()
            payload = {
                    'id': row.id,
                    'new_state': row.enabled,
                    }
            AdminLogManager.post('Banphrase toggled',
                    options['user'],
                    'Enabled' if row.enabled else 'Disabled',
                    row.phrase)
            SocketClientManager.send('banphrase.update', payload)
            return {'success': 'successful toggle', 'new_state': new_state}
开发者ID:Nacht123,项目名称:pajbot,代码行数:28,代码来源:banphrases.py

示例4: generic_toggle

def generic_toggle(route_key, row_id, **options):
    valid_routes = {
            'timer': Timer,
            'banphrase': Banphrase,
            'module': Module,
            }

    route_name = {
            'timer': lambda x: x.name,
            'banphrase': lambda x: x.phrase,
            'module': lambda x: x.id,
            }

    route_title = {
            'timer': 'Timer',
            'banphrase': 'Banphrase',
            'module': 'Module',
            }

    route_validator = {
            'module': lambda x: validate_module(x.id)
            }

    if route_key not in valid_routes:
        return make_response(jsonify({'error': 'Invalid route.'}), 400)
    if 'new_state' not in request.form:
        return make_response(jsonify({'error': 'Missing `new_state` parameter.'}), 400)
    try:
        new_state = int(request.form['new_state'])
    except (ValueError, KeyError):
        return make_response(jsonify({'error': 'Invalid `new_state` parameter.'}), 400)

    route_value = valid_routes[route_key]

    with DBManager.create_session_scope() as db_session:
        row = db_session.query(route_value).filter_by(id=row_id).one_or_none()
        if row:
            validator = route_validator.get(route_key, None)

            if validator is not None:
                res = validator(row)
                if not res:
                    return make_response(jsonify({'error': 'cannot modify {}'.format(route_key)}), 400)

            row.enabled = True if new_state == 1 else False
            db_session.commit()
            payload = {
                    '{}_id'.format(route_key): row.id,  # remove this
                    'id': row.id,
                    'new_state': row.enabled,
                    }
            AdminLogManager.post('{title} toggled'.format(title=route_title[route_key]),
                    options['user'],
                    'Enabled' if row.enabled else 'Disabled',
                    route_name[route_key](row))
            SocketClientManager.send('{}.update'.format(route_key), payload)
            return make_response(jsonify({'success': 'successful toggle', 'new_state': new_state}))
        else:
            return make_response(jsonify({'error': 'invalid {} id'.format(route_key)}))
开发者ID:TalVivian,项目名称:pajbot,代码行数:59,代码来源:api.py

示例5: timer_remove

def timer_remove(timer_id, **options):
    with DBManager.create_session_scope() as db_session:
        timer = db_session.query(Timer).filter_by(id=timer_id).one_or_none()
        if timer is None:
            return make_response(jsonify({"error": "Invalid timer ID"}))
        db_session.delete(timer)
        SocketClientManager.send("timer.remove", {"timer_id": timer.id})
        return make_response(jsonify({"success": "good job"}))
开发者ID:SnackMcOgrelord,项目名称:pajbot,代码行数:8,代码来源:api.py

示例6: banphrase_remove

def banphrase_remove(banphrase_id, **options):
    with DBManager.create_session_scope() as db_session:
        banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()
        if banphrase is None:
            return make_response(jsonify({"error": "Invalid banphrase ID"}))
        db_session.delete(banphrase)
        db_session.delete(banphrase.data)
        SocketClientManager.send("banphrase.remove", {"banphrase_id": banphrase.id})
        return make_response(jsonify({"success": "good job"}))
开发者ID:SnackMcOgrelord,项目名称:pajbot,代码行数:9,代码来源:api.py

示例7: timers_create

    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)

            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)
                    timer.set(**options)
                else:
                    db_session.add(timer)

            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')
开发者ID:SanderVDA,项目名称:pajbot,代码行数:57,代码来源:timers.py

示例8: get

 def get(self, timer_id, **options):
     with DBManager.create_session_scope() as db_session:
         timer = db_session.query(Timer).filter_by(id=timer_id).one_or_none()
         if timer is None:
             return {'error': 'Invalid timer ID'}, 404
         AdminLogManager.post('Timer removed', options['user'], timer.name)
         db_session.delete(timer)
         SocketClientManager.send('timer.remove', {'id': timer.id})
         return {'success': 'good job'}
开发者ID:Nacht123,项目名称:pajbot,代码行数:9,代码来源:timers.py

示例9: get

 def get(self, banphrase_id, **options):
     with DBManager.create_session_scope() as db_session:
         banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()
         if banphrase is None:
             return {'error': 'Invalid banphrase ID'}, 404
         AdminLogManager.post('Banphrase removed', options['user'], banphrase.phrase)
         db_session.delete(banphrase)
         db_session.delete(banphrase.data)
         SocketClientManager.send('banphrase.remove', {'id': banphrase.id})
         return {'success': 'good job'}, 200
开发者ID:Nacht123,项目名称:pajbot,代码行数:10,代码来源:banphrases.py

示例10: modules_edit

def modules_edit(module_id, **options):
    module_manager = ModuleManager(None).load(do_reload=False)
    current_module = find(lambda m: m.ID == module_id, module_manager.all_modules)

    if current_module is None:
        return render_template('admin/module_404.html'), 404

    if request.method == 'POST':
        form_values = {key: value for key, value in request.form.items()}
        res = current_module.parse_settings(**form_values)
        if res is False:
            return render_template('admin/module_404.html'), 404

        with DBManager.create_session_scope() as db_session:
            db_module = db_session.query(Module).filter_by(id=module_id).one_or_none()
            if db_module is None:
                return render_template('admin/module_404.html'), 404

            db_module.settings = json.dumps(res)
            db_session.commit()

            current_module.db_module = db_module

            settings = None
            try:
                settings = json.loads(db_module.settings)
            except (TypeError, ValueError):
                pass
            current_module.load(settings=settings)

            SocketClientManager.send('module.update', {'module_id': db_module.id})

            return render_template('admin/configure_module.html',
                    module=current_module)
        pass
    else:
        with DBManager.create_session_scope() as db_session:
            db_module = db_session.query(Module).filter_by(id=module_id).one_or_none()
            if db_module is None:
                return render_template('admin/module_404.html'), 404

            current_module.db_module = db_module

            settings = None
            try:
                settings = json.loads(db_module.settings)
            except (TypeError, ValueError):
                pass
            current_module.load(settings=settings)

            return render_template('admin/configure_module.html',
                    module=current_module)
开发者ID:gigglearrows,项目名称:pajbot,代码行数:52,代码来源:admin.py

示例11: post

    def post(self, **options):
        args = self.post_parser.parse_args()
        with DBManager.create_session_scope() as db_session:
            twitter_user = db_session.query(TwitterUser).filter_by(username=args['username']).one_or_none()
            if twitter_user is None:
                return {
                        'message': 'We are not following a twitter user by that name.',
                        }, 404

            db_session.delete(twitter_user)
            db_session.flush()
            db_session.commit()

            SocketClientManager.send('twitter.unfollow', {'username': args['username']})

            return {
                    'message': 'Successfully unfollowed {}'.format(args['username']),
                    }, 200
开发者ID:Nacht123,项目名称:pajbot,代码行数:18,代码来源:twitter.py

示例12: generic_toggle

def generic_toggle(route_key, row_id, **options):
    valid_routes = {"timer": Timer, "banphrase": Banphrase, "module": Module}

    if route_key not in valid_routes:
        return make_response(jsonify({"error": "Invalid route."}), 400)
    if "new_state" not in request.form:
        return make_response(jsonify({"error": "Missing `new_state` parameter."}), 400)
    try:
        new_state = int(request.form["new_state"])
    except (ValueError, KeyError):
        return make_response(jsonify({"error": "Invalid `new_state` parameter."}), 400)

    route_value = valid_routes[route_key]

    with DBManager.create_session_scope() as db_session:
        row = db_session.query(route_value).filter_by(id=row_id).one_or_none()
        if row:
            row.enabled = True if new_state == 1 else False
            db_session.commit()
            SocketClientManager.send("{}.update".format(route_key), {"{}_id".format(route_key): row.id})
            return make_response(jsonify({"success": "successful toggle", "new_state": new_state}))
        else:
            return make_response(jsonify({"error": "invalid {} id".format(route_key)}))
开发者ID:SnackMcOgrelord,项目名称:pajbot,代码行数:23,代码来源:api.py

示例13: get

    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
开发者ID:jardg,项目名称:pajbot,代码行数:18,代码来源:commands.py

示例14: init

def init(args):
    import configparser
    import datetime
    import logging
    import subprocess
    import sys

    from flask import request
    from flask import session
    from flask_scrypt import generate_random_salt

    import pajbot.web.common
    import pajbot.web.routes
    from pajbot.bot import Bot
    from pajbot.managers.db import DBManager
    from pajbot.managers.redis import RedisManager
    from pajbot.managers.time import TimeManager
    from pajbot.models.module import ModuleManager
    from pajbot.models.sock import SocketClientManager
    from pajbot.streamhelper import StreamHelper
    from pajbot.utils import load_config
    from pajbot.web.models import errors
    from pajbot.web.utils import download_logo

    log = logging.getLogger(__name__)

    config = configparser.ConfigParser()

    config = load_config(args.config)
    config.read('webconfig.ini')

    if 'web' not in config:
        log.error('Missing [web] section in config.ini')
        sys.exit(1)

    if 'pleblist_password_salt' not in config['web']:
        salt = generate_random_salt()
        config.set('web', 'pleblist_password_salt', salt.decode('utf-8'))

    if 'pleblist_password' not in config['web']:
        salt = generate_random_salt()
        config.set('web', 'pleblist_password', salt.decode('utf-8'))

    if 'secret_key' not in config['web']:
        salt = generate_random_salt()
        config.set('web', 'secret_key', salt.decode('utf-8'))

    if 'logo' not in config['web']:
        res = download_logo(config['webtwitchapi']['client_id'], config['main']['streamer'])
        if res:
            config.set('web', 'logo', 'set')

    StreamHelper.init_web(config['main']['streamer'])

    redis_options = {}
    if 'redis' in config:
        redis_options = config._sections['redis']

    RedisManager.init(**redis_options)

    with open(args.config, 'w') as configfile:
        config.write(configfile)

    app.bot_modules = config['web'].get('modules', '').split()
    app.bot_commands_list = []
    app.bot_config = config
    app.secret_key = config['web']['secret_key']

    if 'sock' in config and 'sock_file' in config['sock']:
        SocketClientManager.init(config['sock']['sock_file'])

    DBManager.init(config['main']['db'])
    TimeManager.init_timezone(config['main'].get('timezone', 'UTC'))

    app.module_manager = ModuleManager(None).load()

    pajbot.web.routes.admin.init(app)
    pajbot.web.routes.api.init(app)
    pajbot.web.routes.base.init(app)

    pajbot.web.common.filters.init(app)
    pajbot.web.common.assets.init(app)
    pajbot.web.common.tasks.init(app)
    pajbot.web.common.menu.init(app)

    app.register_blueprint(pajbot.web.routes.clr.page)

    errors.init(app, config)
    pajbot.web.routes.clr.config = config

    version = Bot.version
    last_commit = ''
    commit_number = 0
    try:
        current_branch = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf8').strip()
        latest_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf8').strip()[:8]
        commit_number = subprocess.check_output(['git', 'rev-list', 'HEAD', '--count']).decode('utf8').strip()
        last_commit = subprocess.check_output(['git', 'log', '-1', '--format=%cd']).decode('utf8').strip()
        version = '{0} DEV ({1}, {2}, commit {3})'.format(version, current_branch, latest_commit, commit_number)
    except:
#.........这里部分代码省略.........
开发者ID:jardg,项目名称:pajbot,代码行数:101,代码来源:__init__.py

示例15: command_update

def command_update(command_id, **options):
    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).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)
        parsed_action = json.loads(command.action_json)
        options = {}

        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

        command.set(**options)

    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'}))
开发者ID:gigglearrows,项目名称:pajbot,代码行数:70,代码来源:api.py


注:本文中的pajbot.models.sock.SocketClientManager类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。