Ejemplo n.º 1
0
 def build_slack_block_native(cls, msg1, msg2, data):
     blocks: List[SectionBlock] = [
         SectionBlock(text=MarkdownTextObject.parse(f"*{msg1}*:\n{msg2}")),
         SectionBlock(fields=[]),
     ]
     names: List[str] = list(set(data.keys()) - set("user_comments"))
     fields = [
         MarkdownTextObject.parse(f"*{name}*:\n{data[name]}") for name in names
     ]
     blocks[1].fields = fields
     return list(b.to_dict() for b in blocks)
Ejemplo n.º 2
0
 def test_home_tab_construction(self):
     home_tab_view = View(
         type="home",
         blocks=[
             SectionBlock(
                 text=MarkdownTextObject(
                     text="*Here's what you can do with Project Tracker:*"
                 ),
             ),
             ActionsBlock(
                 elements=[
                     ButtonElement(
                         text=PlainTextObject(text="Create New Task", emoji=True),
                         style="primary",
                         value="create_task",
                     ),
                     ButtonElement(
                         text=PlainTextObject(text="Create New Project", emoji=True),
                         value="create_project",
                     ),
                     ButtonElement(
                         text=PlainTextObject(text="Help", emoji=True),
                         value="help",
                     ),
                 ],
             ),
             ContextBlock(
                 elements=[
                     ImageElement(
                         image_url="https://api.slack.com/img/blocks/bkb_template_images/placeholder.png",
                         alt_text="placeholder",
                     ),
                 ],
             ),
             SectionBlock(
                 text=MarkdownTextObject(text="*Your Configurations*"),
             ),
             DividerBlock(),
             SectionBlock(
                 text=MarkdownTextObject(
                     text="*#public-relations*\n<fakelink.toUrl.com|PR Strategy 2019> posts new tasks, comments, and project updates to <fakelink.toChannel.com|#public-relations>"
                 ),
                 accessory=ButtonElement(
                     text=PlainTextObject(text="Edit", emoji=True),
                     value="public-relations",
                 ),
             ),
         ],
     )
     home_tab_view.validate_json()
Ejemplo n.º 3
0
def linked_labeled_button_block(
    url: str,
    label_text: str,
    button_text: str,
    value: str,
    action_id: str,
) -> dict[str, str]:
    """
    Generate labeled button block.

    Linked labeled buttons have the link label text on the left and the button on the right.

    Args:
        url (str): URL for label.
        label_text (str): Label text to display.
        button_text (str): Button text to display.
        value (str): Hidden value to assign to the button.
        action_id (str): Action identifier to assign to the button.

    Returns:
        dict: View block with desired button.

    """
    return SectionBlock(
        text=MarkdownTextObject.from_link(link=Link(
            url=url,
            text=label_text,
        )),
        accessory=ButtonElement(
            text=button_text,
            value=value,
            action_id=action_id,
        ),
    ).to_dict()
Ejemplo n.º 4
0
async def events(event: EventCallback):
    if event.type == 'url_verification':
        # AppにRequest URLを登録した際に初回だけ送信されるURLの検証
        # ref: https://api.slack.com/events/url_verification
        return JSONResponse({'challenge': event.challenge})
    try:
        team_conf = TeamConf.get(event.team_id)
    except TeamConf.DoesNotExist:
        return Response(status_code=HTTPStatus.BAD_REQUEST)
    client = WebClient(team_conf.access_token)
    if event.event:
        if event.event.type == 'reaction_added':
            # 投稿にemojiでリアクションがあったイベントを処理する
            # ref: https://api.slack.com/events/reaction_added
            if event.event.reaction in team_conf.emoji_set:
                # リアクションのemojiが設定されている場合
                if event.event.item:
                    item = event.event.item
                    url = client.chat_getPermalink(
                        channel=item.channel,
                        message_ts=item.ts).get('permalink')
                    blocks = [
                        SectionBlock(text=MarkdownTextObject(text=f'<{url}>')),
                        ActionsBlock(elements=[
                            ButtonElement(text='読んだ',
                                          action_id='mark_as_read',
                                          value='mark_as_read')
                        ])
                    ]
                    client.chat_postMessage(text=url,
                                            channel=event.event.user,
                                            unfurl_links=True,
                                            blocks=blocks)
    return Response()
Ejemplo n.º 5
0
    def test_text_length_with_object(self):
        with self.assertRaises(SlackObjectFormationError):
            plaintext = PlainTextObject(text=STRING_301_CHARS)
            ConfirmObject(title="title", text=plaintext).to_dict()

        with self.assertRaises(SlackObjectFormationError):
            markdown = MarkdownTextObject(text=STRING_301_CHARS)
            ConfirmObject(title="title", text=markdown).to_dict()
Ejemplo n.º 6
0
    def test_basic_json(self):
        self.assertDictEqual(
            {
                "text": "some text",
                "type": "mrkdwn"
            },
            MarkdownTextObject(text="some text").to_dict(),
        )

        self.assertDictEqual(
            {
                "text": "some text",
                "verbatim": True,
                "type": "mrkdwn"
            },
            MarkdownTextObject(text="some text", verbatim=True).to_dict(),
        )
Ejemplo n.º 7
0
def markdown_block(text: str) -> dict[str, str]:
    """
    Generate general Markdown block.

    Args:
        text (str): Markdown text to display.

    Returns:
        dict: View block with desired Markdown text.

    """
    return SectionBlock(text=MarkdownTextObject(text=text)).to_dict()
Ejemplo n.º 8
0
 def test_from_list_of_json_objects(self):
     json_objects = [
         PlainTextObject.from_str("foo"),
         MarkdownTextObject.from_str("bar"),
     ]
     output = extract_json(json_objects)
     expected = {
         "result": [
             {"type": "plain_text", "text": "foo", "emoji": True},
             {"type": "mrkdwn", "text": "bar"},
         ]
     }
     self.assertDictEqual(expected, {"result": output})
Ejemplo n.º 9
0
    def test_passing_text_objects(self):
        direct_construction = ConfirmObject(title="title",
                                            text="Are you sure?")

        mrkdwn = MarkdownTextObject(text="Are you sure?")

        preconstructed = ConfirmObject(title="title", text=mrkdwn)

        self.assertDictEqual(direct_construction.to_dict(),
                             preconstructed.to_dict())

        plaintext = PlainTextObject(text="Are you sure?", emoji=False)

        passed_plaintext = ConfirmObject(title="title", text=plaintext)

        self.assertDictEqual(
            {
                "confirm": {
                    "emoji": True,
                    "text": "Yes",
                    "type": "plain_text"
                },
                "deny": {
                    "emoji": True,
                    "text": "No",
                    "type": "plain_text"
                },
                "text": {
                    "emoji": False,
                    "text": "Are you sure?",
                    "type": "plain_text"
                },
                "title": {
                    "emoji": True,
                    "text": "title",
                    "type": "plain_text"
                },
            },
            passed_plaintext.to_dict(),
        )
Ejemplo n.º 10
0
 def test_valid_construction(self):
     modal_view = View(
         type="modal",
         callback_id="modal-id",
         title=PlainTextObject(text="Awesome Modal"),
         submit=PlainTextObject(text="Submit"),
         close=PlainTextObject(text="Cancel"),
         blocks=[
             InputBlock(
                 block_id="b-id",
                 label=PlainTextObject(text="Input label"),
                 element=PlainTextInputElement(action_id="a-id"),
             ),
             InputBlock(
                 block_id="cb-id",
                 label=PlainTextObject(text="Label"),
                 element=CheckboxesElement(
                     action_id="a-cb-id",
                     options=[
                         Option(
                             text=PlainTextObject(
                                 text="*this is plain_text text*"),
                             value="v1",
                         ),
                         Option(
                             text=MarkdownTextObject(
                                 text="*this is mrkdwn text*"),
                             value="v2",
                         ),
                     ],
                 ),
             ),
             SectionBlock(
                 block_id="sb-id",
                 text=MarkdownTextObject(
                     text="This is a mrkdwn text section block."),
                 fields=[
                     PlainTextObject(text="*this is plain_text text*",
                                     emoji=True),
                     MarkdownTextObject(text="*this is mrkdwn text*"),
                     PlainTextObject(text="*this is plain_text text*",
                                     emoji=True),
                 ],
             ),
             DividerBlock(),
             SectionBlock(
                 block_id="rb-id",
                 text=MarkdownTextObject(
                     text=
                     "This is a section block with radio button accessory"),
                 accessory=RadioButtonsElement(
                     initial_option=Option(
                         text=PlainTextObject(text="Option 1"),
                         value="option 1",
                         description=PlainTextObject(
                             text="Description for option 1"),
                     ),
                     options=[
                         Option(
                             text=PlainTextObject(text="Option 1"),
                             value="option 1",
                             description=PlainTextObject(
                                 text="Description for option 1"),
                         ),
                         Option(
                             text=PlainTextObject(text="Option 2"),
                             value="option 2",
                             description=PlainTextObject(
                                 text="Description for option 2"),
                         ),
                     ],
                 ),
             ),
         ],
     )
     modal_view.validate_json()
Ejemplo n.º 11
0
def handle_command(body: dict, ack: Ack, respond: Respond, client: WebClient,
                   logger: Logger) -> None:
    logger.info(body)
    ack(
        text="Accepted!",
        blocks=[
            SectionBlock(
                block_id="b",
                text=MarkdownTextObject(text=":white_check_mark: Accepted!"),
            )
        ],
    )

    respond(blocks=[
        SectionBlock(
            block_id="b",
            text=MarkdownTextObject(
                text="You can add a button alongside text in your message. "),
            accessory=ButtonElement(
                action_id="a",
                text=PlainTextObject(text="Button"),
                value="click_me_123",
            ),
        ),
    ])

    res = client.views_open(
        trigger_id=body["trigger_id"],
        view=View(
            type="modal",
            callback_id="view-id",
            title=PlainTextObject(text="My App"),
            submit=PlainTextObject(text="Submit"),
            close=PlainTextObject(text="Cancel"),
            blocks=[
                InputBlock(
                    element=PlainTextInputElement(action_id="text"),
                    label=PlainTextObject(text="Label"),
                ),
                InputBlock(
                    block_id="es_b",
                    element=ExternalDataSelectElement(
                        action_id="es_a",
                        placeholder=PlainTextObject(text="Select an item"),
                        min_query_length=0,
                    ),
                    label=PlainTextObject(text="Search"),
                ),
                InputBlock(
                    block_id="mes_b",
                    element=ExternalDataMultiSelectElement(
                        action_id="mes_a",
                        placeholder=PlainTextObject(text="Select an item"),
                        min_query_length=0,
                    ),
                    label=PlainTextObject(text="Search (multi)"),
                ),
            ],
        ),
    )
    logger.info(res)
Ejemplo n.º 12
0
 def test_from_string(self):
     markdown = MarkdownTextObject(text="some text")
     self.assertDictEqual(
         markdown.to_dict(),
         MarkdownTextObject.direct_from_string("some text"))