Pular para conteúdo

Messenger

The Messenger Module represents a generic messaging service, used to abstract the characteristics common to all messaging services used in the project.

Classes

Message: str Name that identifies the messaging service Messenger: List[Message] List of messages to send RecipientFormatError: Custom error that is raised when a recipients doesn't have the rigth format.

Message

Bases: BaseModel

Represents a generic message used in all messengers.

Attributes:

Name Type Description
sender str

Contact of the sender of the message

recipients List[str]

List of contacts who will receive the message

subject Optional[str]

Message subject is optional

body str

message body, content that will be sent to recipients

Source code in messenger/messenger.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Message(BaseModel):
    """
    Represents a generic message used in all messengers.

    Attributes:
        sender: Contact of the sender of the message
        recipients: List of contacts who will receive the message
        subject: Message subject is optional
        body: message body, content that will be sent to recipients
    """

    sender: str
    recipients: List[str]
    subject: Optional[str]
    body: str
    type: str = 'text'

MessageNotSendError

Bases: Exception

Custom error that is raised when a message is not sended to a recipient.

Source code in messenger/messenger.py
32
33
34
35
36
37
38
class MessageNotSendError(Exception):
    """Custom error that is raised when a message is not sended to a recipient."""

    def __init__(self, value: str, message: str) -> None:
        self.value = value
        self.message = message
        super().__init__(message)

Messenger

Bases: ABC, BaseModel

Represents a generic messaging service, used to abstract the characteristics common to all messaging services used in the project.

Attributes:

Name Type Description
name str

str Name that identifies the messaging service

messages List[Message]

List[Message] List of messages to send

credentials Dict

Dict Dictionary with the information needed to connect the service

engine Any

Any Object that contains methods for sending messages

Source code in messenger/messenger.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
class Messenger(ABC, BaseModel):
    """
    Represents a generic messaging service, used to abstract the characteristics common to all messaging services used in the project.

    Attributes:
        name: str Name that identifies the messaging service
        messages: List[Message] List of messages to send
        credentials: Dict Dictionary with the information needed to connect the service
        engine: Any Object that contains methods for sending messages
    """

    name: str
    messages: List[Message] = []
    credentials: Dict
    engine: Any = None

    @abstractmethod
    def _validate_message_recipients(message: Message) -> Message:
        """
        Checks whether the recipients of a given message are valid using validator module and pydantic validation especfications. The type of recipient changes according to the used messenger

        Args:
            message: Individual message to check recipients

        Returns:
            The given message if all recipients is valid

        Raises:
            RecipientFormatError: If at least one of the recipients is not valid.
        """
        ...

    @classmethod
    @abstractmethod
    def recipientsValid(cls, message: Message):
        """
        Calls _validate_message_recipients to check whether the recipients of a all messages in the messenger are valids. Uses pydantic validator decorator to iterate over all messages

        Args:
            message: Message to check recipients

        Raises:
            RecipientFormatError: If at least one of the recipients is not valid.
        """
        ...

    @abstractmethod
    def connect(self) -> int:
        """
        Connect with the messaging service using self.credentials for the necessary information to connect (eg Login and Password or API-Token) and updates the 'engine' attribute with the service created for sending messages if any success.

        Returns:
            An integer that represents the status code obeying the http service status code standard (eg: 200 to success and 404 to not found error).

        Raises:
            Exception: If there is any problem with the service trying to connect
        """
        ...

    @abstractmethod
    def _sendMessage(self, message: Message) -> int:
        """
        Helper method that implements sending a single message to its recipients

        Args:
            message: Individual message to sent to all recipients

        Returns:
            An integer that represents the status code obeying the http service status code standard (eg: 200 to success and 404 to not found error).

        Raises:
            Exception: If there is any problem with the service trying to send message.
        """
        ...

    def sendMessage(self, messages: List[Message] = None) -> int:
        """
        Calls _sendMessage to send all messages from a list to their respective recipients, if it does not receive a list as a parameter it sends all messages belonging to the messages attribute

        Args:
            messages: A list of Individual messages to send, it's optional

        Returns:
            An integer that's represents the amount of sent messages

        Raises:
            Exception: If there is any problem with the service trying to send message.
        """

        sent_messages = 0
        selected_messages = self.messages
        if messages:
            selected_messages = messages

        for message in selected_messages:
            try:
                sent_messages += 1 if self._sendMessage(message) == 200 else 0
            except Exception as e:
                raise e

        return sent_messages

connect() abstractmethod

Connect with the messaging service using self.credentials for the necessary information to connect (eg Login and Password or API-Token) and updates the 'engine' attribute with the service created for sending messages if any success.

Returns:

Type Description
int

An integer that represents the status code obeying the http service status code standard (eg: 200 to success and 404 to not found error).

Raises:

Type Description
Exception

If there is any problem with the service trying to connect

Source code in messenger/messenger.py
105
106
107
108
109
110
111
112
113
114
115
116
@abstractmethod
def connect(self) -> int:
    """
    Connect with the messaging service using self.credentials for the necessary information to connect (eg Login and Password or API-Token) and updates the 'engine' attribute with the service created for sending messages if any success.

    Returns:
        An integer that represents the status code obeying the http service status code standard (eg: 200 to success and 404 to not found error).

    Raises:
        Exception: If there is any problem with the service trying to connect
    """
    ...

recipientsValid(message) abstractmethod classmethod

Calls _validate_message_recipients to check whether the recipients of a all messages in the messenger are valids. Uses pydantic validator decorator to iterate over all messages

Parameters:

Name Type Description Default
message Message

Message to check recipients

required

Raises:

Type Description
RecipientFormatError

If at least one of the recipients is not valid.

Source code in messenger/messenger.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
@classmethod
@abstractmethod
def recipientsValid(cls, message: Message):
    """
    Calls _validate_message_recipients to check whether the recipients of a all messages in the messenger are valids. Uses pydantic validator decorator to iterate over all messages

    Args:
        message: Message to check recipients

    Raises:
        RecipientFormatError: If at least one of the recipients is not valid.
    """
    ...

sendMessage(messages=None)

Calls _sendMessage to send all messages from a list to their respective recipients, if it does not receive a list as a parameter it sends all messages belonging to the messages attribute

Parameters:

Name Type Description Default
messages List[Message]

A list of Individual messages to send, it's optional

None

Returns:

Type Description
int

An integer that's represents the amount of sent messages

Raises:

Type Description
Exception

If there is any problem with the service trying to send message.

Source code in messenger/messenger.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def sendMessage(self, messages: List[Message] = None) -> int:
    """
    Calls _sendMessage to send all messages from a list to their respective recipients, if it does not receive a list as a parameter it sends all messages belonging to the messages attribute

    Args:
        messages: A list of Individual messages to send, it's optional

    Returns:
        An integer that's represents the amount of sent messages

    Raises:
        Exception: If there is any problem with the service trying to send message.
    """

    sent_messages = 0
    selected_messages = self.messages
    if messages:
        selected_messages = messages

    for message in selected_messages:
        try:
            sent_messages += 1 if self._sendMessage(message) == 200 else 0
        except Exception as e:
            raise e

    return sent_messages

RecipientFormatError

Bases: Exception

Custom error that is raised when a recipients doesn't have the rigth format.

Attributes:

Name Type Description
value

Exception value error

message

Error message

Source code in messenger/messenger.py
17
18
19
20
21
22
23
24
25
26
27
28
29
class RecipientFormatError(Exception):
    """
    Custom error that is raised when a recipients doesn't have the rigth format.

    Attributes:
        value: Exception value error
        message: Error message
    """

    def __init__(self, value: str, message: str) -> None:
        self.value = value
        self.message = message
        super().__init__(message)