Esempio n. 1
1
def edit_rules():
    """Edit rules

    Edit the rules that process inbound events"""
    my_rules = rules.get_all_rules()
    my_rules.append(DEFAULT_RULE)

    selected_rule_id = select(
        label="Existing rules",
        options=[{
            "label": rule["name"],
            "value": rule["id"]
        } for rule in my_rules],
    )
    # Rules have unique IDs from the database:
    logging.info(f"selected_rule: {selected_rule_id}")
    use_rule = [r for r in my_rules if r["id"] == int(selected_rule_id)][0]
    updated_rule = input_group(
        "Rule editing",
        [
            input("name",
                  type=TEXT,
                  name="name",
                  value=use_rule["name"],
                  required=True),  # Need ttextarea(
            textarea(
                "Rule names",
                name="rule",
                rows=10,
                code={
                    "mode": "python",  # code language
                    "theme":
                    "darcula",  # Codemirror theme. Visit https://codemirror.net/demo/theme.html#cobalt to get more themes
                },
                value=f"""{use_rule['rule']}\n""",
            ),
            actions(
                "actions",
                [
                    # {"label": "test", "value": "test"},
                    {
                        "label": "save",
                        "value": "save"
                    },
                ],
                name="action",
                help_text="Save",
            ),
        ],
    )
    if updated_rule is not None:
        rl = dict(updated_rule)
        if rl["action"] == "save":
            rule_info = rules.save_rule(rl["name"], rl["rule"],
                                        selected_rule_id)
            put_row(put_text("Rule"))
            put_row(put_code(pprint.pformat(rule_info, indent=1)))
            # Use webhook_info's ID to add/update the extractor

    put_text(f"The rule added is: {updated_rule}")
Esempio n. 2
0
async def main():
    """PyWebIO聊天室
    和当前所有在线的人聊天
    """
    global chat_msgs
    # run_js("alert('233')")
    put_markdown(
        "## PyWebIO聊天室\n欢迎来到聊天室,你可以和当前所有在线的人聊天。你可以在浏览器的多个标签页中打开本页面来测试聊天效果。"
        "本应用使用不到80行代码实现,源代码[链接](https://github.com/wang0618/PyWebIO/blob/dev/demos/chat_room.py)",
        lstrip=True)

    msg_box = output()
    put_scrollable(msg_box, height=300, keep_bottom=True)
    nickname = await input("请输入你的昵称",
                           required=True,
                           validate=lambda n: '昵称已被使用'
                           if n in online_users or n == '📢' else None)

    online_users.add(nickname)
    chat_msgs.append(
        ('📢', '`%s`加入聊天室. 当前在线人数 %s' % (nickname, len(online_users))))
    msg_box.append(
        put_markdown('`📢`: `%s`加入聊天室. 当前在线人数 %s' %
                     (nickname, len(online_users))))

    @defer_call
    def on_close():
        online_users.remove(nickname)
        chat_msgs.append(
            ('📢', '`%s`退出聊天室. 当前在线人数 %s' % (nickname, len(online_users))))

    refresh_task = run_async(refresh_msg(nickname, msg_box))

    while True:
        data = await input_group(
            '发送消息', [
                input(name='msg', help_text='消息内容支持行内Markdown语法'),
                actions(
                    name='cmd',
                    buttons=['发送', '多行输入', {
                        'label': '退出',
                        'type': 'cancel'
                    }])
            ],
            validate=lambda d: ('msg', '消息不为空')
            if d['cmd'] == '发送' and not d['msg'] else None)
        if data is None:
            break
        if data['cmd'] == '多行输入':
            data['msg'] = '\n' + await textarea(
                '消息内容', help_text='消息内容支持Markdown语法', required=True)
        msg_box.append(
            put_markdown('`%s`: %s' % (nickname, data['msg']), sanitize=True))
        msg_box.append(put_markdown(str(chat_msgs), sanitize=True))
        chat_msgs.append((nickname, data['msg']))

    refresh_task.close()
    toast("你已经退出聊天室")
Esempio n. 3
0
def edit_webhook():
    """Edit webhook and its extractor

    This should be changed to work with a programattically named
    webhook that has a randmoly named inbound address. For now, we
    name it I guess

    """
    my_hooks = extractions.get_all_webhooks()
    my_hooks.append({
        "id": 0,
        "name": "Your new webhook could go here!",
        "path": "Enter the path that this will be matched on",
        "queue_name": "base name for the queue",
    })

    selected_hook_id = select(
        label="Existing webhooks",
        options=[{
            "label": hook.get("name", "No hook name found"),
            "value": hook.get("id", 0),
        } for hook in my_hooks],
    )
    # Rules have unique IDs from the database:
    logging.info(f"selected_hook: {selected_hook_id}")

    my_hook = dict()
    my_extractor = dict()
    my_hook.update(DEFAULT_HOOK)
    my_extractor.update(DEFAULT_EXTRACTOR)
    if selected_hook_id != 0:
        my_hook = extractions.get_webhook(selected_hook_id)
        my_extractor = extractions.get_hook_extractor(selected_hook_id)

    # TODO: update validator to avoid default hook 0 names
    updated_extractor = input_group(
        "Hook data and hook extractor",
        [
            input("name",
                  type=TEXT,
                  name="name",
                  value=my_hook["name"],
                  required=True),  # Need to get a way to carry around the IDs
            input("path",
                  type=TEXT,
                  name="path",
                  value=my_hook["path"],
                  required=True),  # Need to get a way to carry around the IDs
            input(
                "queue_name",
                type=TEXT,
                name="queue_name",
                value=my_hook["queue_name"],
                required=True,
            ),  # Need to get a way to carry around the IDs
            textarea(
                "Example message",
                name="example",
                rows=10,
                code={
                    "mode": "python",  # code language
                    "theme":
                    "darcula",  # Codemirror theme. Visit https://codemirror.net/demo/theme.html#cobalt to get more themes
                },
                value=my_extractor["example"],
            ),
            textarea(
                "Edit an extraction rule",
                name="extractor",
                rows=10,
                code={
                    "mode": "python",  # code language
                    "theme":
                    "darcula",  # Codemirror theme. Visit https://codemirror.net/demo/theme.html#cobalt to get more themes
                },
                value=my_extractor["extractor"],
            ),
            actions(
                "actions",
                [
                    {
                        "label": "test",
                        "value": "test"
                    },
                    {
                        "label": "save",
                        "value": "save"
                    },
                ],
                name="action",
                help_text="Save or test",
            ),
        ],
        validate=test_extractor,
    )
    # Pretty much can't be none, but let's follow the example from
    # https://pywebio.readthedocs.io/en/latest/input.html#pywebio.input.actions
    if updated_extractor is not None:
        uex = dict(updated_extractor)
        if uex["action"] == "save":
            webhook_info = extractions.save_webhook(selected_hook_id,
                                                    uex["name"], uex["path"],
                                                    uex["queue_name"])
            extractor_info = extractions.save_extractor(
                uex["name"], webhook_info["id"], uex["extractor"],
                uex["example"])
            put_row(put_text("Webhook"))
            put_row(put_code(pprint.pformat(webhook_info, indent=1)))
            put_row(put_text("Extractor"))
            put_row(put_code(pprint.pformat(extractor_info, indent=1)))
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

import pywebio.input as inp
import pywebio.output as out


answer = inp.actions(label="test", buttons=["varianta 1", "varianta 2", "varianta 3"])

out.put_info("Odpověď")
out.put_text(answer)
Esempio n. 5
0
    def get_inputs():
        out = []
        old = deep_get(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}',
                       'Key not found!')
        out.append(
            input(
                name=V.lang,
                label=V.lang,
                value=None if V.clear else old,
                help_text=f'{V.group}.{V.arg}.{V.key}',
                placeholder=old,
            ))
        out.append(
            select(name='group',
                   label='Group',
                   options=V.groups,
                   value=V.group,
                   onchange=lambda g: update_var(group=g),
                   required=True))
        out.append(
            select(name='arg',
                   label='Arg',
                   options=V.args,
                   value=V.arg,
                   onchange=lambda a: update_var(arg=a),
                   required=True))
        out.append(
            select(name='key',
                   label='Key',
                   options=V.keys,
                   value=V.key,
                   onchange=lambda k: update_var(key=k),
                   required=True))
        _LANGUAGES = LANGUAGES.copy()
        _LANGUAGES.remove(V.lang)
        for L in _LANGUAGES:
            out.append(
                input(name=L,
                      label=L,
                      readonly=True,
                      value=deep_get(dict_lang[L],
                                     f'{V.group}.{V.arg}.{V.key}',
                                     'Key not found!')))
        out.append(
            actions(name='action',
                    buttons=[
                        {
                            "label": "Next",
                            "value": 'Next',
                            "type": "submit",
                            "color": "success"
                        },
                        {
                            "label": "Next without save",
                            "value": 'Skip',
                            "type": "submit",
                            "color": "secondary"
                        },
                        {
                            "label": "Submit",
                            "value": "Submit",
                            "type": "submit",
                            "color": "primary"
                        },
                        {
                            "label": "Quit and save",
                            "type": "cancel",
                            "color": "secondary"
                        },
                    ]))

        return out