def test_multi_block_attachment() -> None:
    block_0 = SectionBlock("I like pretty colours", block_id="fake_block_id_0")
    block_1 = SectionBlock("I don't like pretty colours",
                           block_id="fake_block_id_1")
    attachment = Attachment(blocks=[block_0, block_1], color=Color.PURPLE)
    with open("test/samples/attachment_multi_block.json", "r") as expected:
        assert expected.read() == repr(attachment)
Exemple #2
0
def test_basic_section_fields() -> None:
    block = SectionBlock(
        "Test:",
        fields=[Text(text='foo', type_=TextType.PLAINTEXT),
                Text(text='bar')],
        block_id="fake_block_id")
    with open("test/samples/section_block_fields.json", "r") as expected:
        assert repr(block) == expected.read()
Exemple #3
0
def handle_leet(command: Command) -> None:
    """
    `!leet [`easy` | `medium` | `hard`] - Retrieves a set of questions from online coding
    websites, and posts in channel with a random question from this set. If a difficulty
    is provided as an argument, the random question will be restricted to this level of
    challenge. Else, a random difficulty is generated to choose.
    """
    was_random = True  # Used for output later

    if command.has_arg():
        if (command.arg not in {"easy", "medium", "hard"}):
            bot.post_message(command.channel_id,
                             "Usage: !leet [`easy` | `medium` | `hard`]")
            return
        else:
            difficulty = command.arg.lower()
            was_random = False
    else:
        difficulty = random.choice(
            LC_DIFFICULTY_MAP)  # No difficulty specified, randomly generate

    # List to store questions collected
    questions: List[Tuple[str, str]] = []

    # Go fetch questions from APIs
    collect_questions(questions, difficulty)
    selected_question = select_question(questions)  # Get a random question

    # If we didn't find any questions for this difficulty, try again, probably timeout on all 3
    if (selected_question is None):
        bot.post_message(
            command.channel_id,
            "Hmm, the internet pipes are blocked. Try that one again.")
        return

    # Leetcode difficulty colors
    color = COLORS[difficulty]

    if (was_random):
        title_text = f"Random {difficulty} question generated!"
    else:
        # Style this a bit nicer
        difficulty = difficulty.title()
        title_text = f"{difficulty} question generated!"

    difficulty = difficulty.title(
    )  # If we haven't already (i.e. random question)

    msg_text = f"Here's a new question for you! <{selected_question[1]}|{selected_question[0]}>"

    bot.post_message(command.channel_id,
                     text=title_text,
                     attachments=[
                         Attachment(SectionBlock(msg_text),
                                    color=color)._resolve()
                     ])
Exemple #4
0
def get_report_blocks(login, text, author=None):
    blocks = [
        SectionBlock(
            f"Report `{login}`:\n{text}",
            accessory=Image(
                image_url=settings.PHOTO_FSTRING_SQUARE.format(login),
                alt_text=login),
        ),
        ContextBlock(f"*By: {author.slack_username}*"),
    ]
    return repr(blocks)
Exemple #5
0
def process_leodagan(state, message):
    texts_to_test = find_code_blocks(message)

    blocks = []
    for text in texts_to_test:
        leodagan_result = launch_leodagan(text).decode("utf-8")
        if not leodagan_result:
            leodagan_result = "La netiquette est conforme."
        blocks.append(SectionBlock(Text(f"```{leodagan_result}```")))

    if blocks:
        send_message(state, text="Léodagan report", blocks=repr(blocks))
Exemple #6
0
def get_photo_blocks(photo_slug, url, stalker=None):
    blocks = [
        SectionBlock(text=f"*{photo_slug}*"),
        ImageBlock(image_url=url, alt_text=photo_slug, title=photo_slug),
    ]
    if not stalker:
        blocks.append(
            ActionsBlock(
                Button(text="Send to Channel",
                       action_id="photo.post",
                       value=photo_slug)))
    else:
        blocks.append(ContextBlock(f"*Stalké Par: {stalker.slack_username}*"))

    return repr(blocks)
Exemple #7
0
    def get_slack_block(self, show_results=True, anonymous=False):
        voter_count = ""
        if show_results:
            voter_count = f"\t`{self.voters.count()}`"

        voters = ""
        if not anonymous:
            voters = f"\n{self.slack_voters}"

        return SectionBlock(
            f"{self.slack_text}{voter_count}{voters}",
            accessory=Button(text="Vote",
                             action_id="polls.vote",
                             value=f"{self.id}"),
        )
Exemple #8
0
    def slack_blocks(self):
        total_votes = UserChoice.objects.filter(
            choice__poll__id=self.id).count()

        blocks = [
            SectionBlock(
                f"*{self.name}*\n\nTotal votes: `{total_votes}`",
                accessory=Button(
                    "Delete Poll",
                    action_id="polls.delete",
                    value=f"{self.id}",
                    confirm=Confirm(
                        "Delete Poll",
                        text="Are you sure you want to delete this poll?"),
                ),
            ),
            DividerBlock(),
            *map(
                lambda c: c.get_slack_block(self.visible_results, self.
                                            anonymous),
                self.choices.order_by("index").prefetch_related(
                    "voters").all(),
            ),
            *([
                ActionsBlock(
                    Button(
                        "Reveal results",
                        action_id="polls.reveal",
                        value=f"{self.id}",
                    ))
            ] if not self.visible_results else []),
            *([
                ActionsBlock(
                    Button(
                        "Add a choice",
                        action_id="polls.new_choice",
                        value=f"{self.id}",
                    ))
            ] if self.open_choice else []),
            ContextBlock(f"*Created By:* {self.creator.slack_username}"),
            ContextBlock(
                f'{timezone.now().strftime("Last updated: %x at %H:%M")}'),
        ]

        return repr(blocks)
Exemple #9
0
def send_modal(state, view, keep_view_id=False):
    if not keep_view_id:
        return settings.SLACK_CLIENT.views_open(trigger_id=state.trigger_id,
                                                view=view)

    res = settings.SLACK_CLIENT.views_open(
        trigger_id=state.trigger_id,
        view=make_modal(state,
                        title="Loading...",
                        blocks=[SectionBlock("Loading...")]),
    )

    view_id = res["view"]["id"]
    private_metadata = json.loads(view["private_metadata"])
    private_metadata["view_id"] = view_id
    view["private_metadata"] = json.dumps(private_metadata)

    settings.SLACK_CLIENT.views_update(view_id=view_id, view=view)
def test_single_attachment() -> None:
    block = SectionBlock("I like pretty colours", block_id="fake_block_id")
    attachment = Attachment(blocks=block, color=Color.BLACK)
    with open("test/samples/attachment_simple.json", "r") as expected:
        assert expected.read() == repr(attachment)
def test_basic_message() -> None:
    block = SectionBlock("Hello, world!", block_id="fake_block_id")
    message = Message(channel="#general", blocks=block)
    with open("test/samples/message_simple.json", "r") as expected:
        assert repr(message) == expected.read()
def test_message_with_attachment() -> None:
    block = SectionBlock("Hello, world!", block_id="fake_block_id")
    attachment = Attachment(blocks=block, color=Color.YELLOW)
    message = Message(channel="#general", attachments=[attachment, ])
    with open("test/samples/message_with_attachments.json", "r") as expected:
        assert repr(message) == expected.read()
Exemple #13
0
 def add_product(self, name: str, url: str, arrival_type: str) -> None:
     text = Text(text="%s!!!\n\n> <%s|%s>" % (arrival_type, url, name))
     self.blocks.append(SectionBlock(text=text))
Exemple #14
0
def _iter_triage(t):
    fields = ['*start_date*', '*end_date*', t.start_date, t.end_date]
    header = SectionBlock(text=t.title, fields=[Text(f)._resolve() for f in fields])
    yield header
    yield from t.currently_failing
    yield from t.eventually_succeeded
Exemple #15
0
def test_message_response() -> None:
    block = SectionBlock("Hello, world!", block_id="fake_block_id")
    message = MessageResponse(blocks=block, ephemeral=True)
    with open("test/samples/message_response.json", "r") as expected:
        assert repr(message) == expected.read()