Passed
Pull Request — main (#330)
by
unknown
01:44
created

pincer.utils.convert_message   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 15
eloc 43
dl 0
loc 73
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
C convert_message() 0 34 9
B list_to_message_dict() 0 9 6
1
# Copyright Pincer 2021-Present
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
# Full MIT License can be found in `LICENSE` at the project root.
3
4
from __future__ import annotations
5
6
from typing import TYPE_CHECKING, Tuple, List
7
from typing import Union
8
9
from ..objects.app.interaction_flags import InteractionFlags
10
from ..objects.message.component import MessageComponent
11
from ..objects.message.embed import Embed
12
from ..objects.message.file import File
13
from ..objects.message.message import Message
14
15
PILLOW_IMPORT = True
16
17
try:
18
    from PIL.Image import Image
19
except (ModuleNotFoundError, ImportError):
20
    PILLOW_IMPORT = False
21
22
if TYPE_CHECKING:
23
    from pincer import Client
24
25
MessageConvertable = Union[Embed, Message, str, Tuple, List]
26
27
28
def convert_message(client: Client, message: MessageConvertable) -> Message:
29
    """
30
    Converts a message to a Message object.
31
32
    Parameters
33
    ----------
34
    client : :class:`~pincer.client.Client`
35
        The Client object for the bot
36
    message : MessageConvertable
37
        A value to be converted to a message
38
39
    Returns
40
    -------
41
    :class:`~pincer.objects.message.message.Message`
42
        The message object to be sent
43
    """
44
    if message and isinstance(message, (tuple, list)):
45
        kwargs = {"attachments": [], "embeds": [], "components": []}
46
        for item in message:
47
            list_to_message_dict(item, kwargs)
48
        message = Message(**kwargs)
49
    elif isinstance(message, Embed):
50
        message = Message(embeds=[message])
51
    elif PILLOW_IMPORT and isinstance(message, (File, Image)):
52
        message = Message(attachments=[message])
53
    elif not isinstance(message, Message):
54
        message = (
55
            Message(message)
56
            if message
57
            else Message(
58
                client.received_message, flags=InteractionFlags.EPHEMERAL
59
            )
60
        )
61
    return message
62
63
64
def list_to_message_dict(item, kwargs):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
65
    if isinstance(item, Embed):
66
        kwargs["embeds"].append(item)
67
    elif PILLOW_IMPORT and isinstance(item, File):
68
        kwargs["attachments"].append(item)
69
    elif isinstance(item, MessageComponent):
70
        kwargs["components"].append(item)
71
    elif isinstance(item, str):
72
        kwargs["content"] = ""
73