Message

Summary

Message(*[, attributes, chat, author, …])

A message.

LinkAttribute(title[, description, image, url])

Attributes for link messages.

LocationAttribute(latitude, longitude)

Attributes for location messages.

StatusAttribute(status_type[, timeout])

Attributes for status messages.

MessageCommands(commands)

Message commands.

MessageCommand(name, callable_name[, args, …])

A message command.

Substitutions(substitutions)

Message text substitutions, or “@-references”.

Classes

class ehforwarderbot.message.Message(*, attributes=None, chat=None, author=None, commands=None, deliver_to=None, edit=False, edit_media=False, file=None, filename=None, is_system=False, mime=None, path=None, reactions=None, substitutions=None, target=None, text='', type=<MsgType.Unsupported: 'Unsupported'>, uid=None, vendor_specific=None)[source]

A message.

Note

Message objects are picklable, thus it is strongly RECOMMENDED to keep any object of its subclass also picklable.

Keyword Arguments
  • attributes (Optional[MessageAttribute]) –

    Attributes used for a specific message type. Only specific message type requires this attribute. Defaulted to None.

    Note

    Do NOT use object of the abstract class MessageAttribute for attributes, but object of specific class instead.

  • chat (Chat) – Sender of the message.

  • author (ChatMember) –

    Author of this message. Author of the message MUST be indicated as a part of the same chat this message is from. If the message is sent from the User Themself, this MUST be an object of SelfChatMember.

    Note that the author MAY not be inside members of the chat of this message. The author MAY have a different module_id from the chat, and could be unretrievable otherwise.

  • commands (Optional[MessageCommands]) –

    Commands attached to the message

    This attribute will be ignored in _Status_ messages.

  • deliver_to (Channel) – The channel that the message is to be delivered to.

  • edit (bool) –

    Flag this up if the message is edited. Flag only this if no multimedia file is modified, otherwise flag up both this one and edit_media as well.

    If no media file is modified, the edited message MAY carry no information about the file.

    This attribute will be ignored in _Status_ messages.

  • edit_media (bool) –

    Flag this up if any file attached to the message is modified. If this value is true, edit MUST also be True. This attribute is ignored if the message type is not supposed to contain any media file, e.g. Text, Location, etc.

    This attribute will be ignored in _Status_ messages.

  • file (Optional[BinaryIO]) – File object to multimedia file, type “rb”. None if N/A. Recommended to use NamedTemporaryFile. The file SHOULD be able to be safely deleted (or otherwise discarded) once closed. All file object MUST be sought back to 0 (file.seek(0)) before sending.

  • filename (Optional[str]) – File name of the multimedia file. None if N/A

  • is_system (bool) – Mark as true if this message is a system message.

  • mime (Optional[str]) – MIME type of the file. None if N/A

  • path (Optional[Path]) – Local path of multimedia file. None if N/A

  • reactions (Dict[str, Collection[Chat]]) –

    Indicate reactions to the message. Dictionary key is the canonical name of reaction, usually an emoji. Value is a collection of users who reacted to the message with that certain emoji. All Chat objects in this dict MUST be members in the chat of this message.

    This attribute will be ignored in _Status_ messages.

  • substitutions (Optional[Substitutions]) –

    Substitutions of messages, usually used when the some parts of the text of the message refers to another user or chat.

    This attribute will be ignored in _Status_ messages.

  • target (Optional[Message]) –

    Target message (usually for messages that “replies to” another message).

    This attribute will be ignored in _Status_ messages.

    Note

    This message MAY be a “minimum message”, with only required fields:

    • Message.chat

    • Message.author

    • Message.text

    • Message.type

    • Message.uid

  • text (str) –

    Text of the message.

    This attribute will be ignored in _Status_ messages.

  • type (MsgType) – Type of message

  • uid (str) –

    Unique ID of message. Usually stores the message ID from slave channel. This ID MUST be unique among all chats in the same channel.

    Note

    Some channels may not support message editing. Some channels may issue a new uid for edited message.

  • vendor_specific (Dict[str, Any]) – A series of vendor specific attributes attached. This can be used by any other channels or middlewares that is compatible with such information. Note that no guarantee is provided for information in this section.

Get the link attributes of the current message, if available.

Return type

Optional[LinkAttribute]

property location

Get the location attributes of the current message, if available.

Return type

Optional[LocationAttribute]

property status

Get the status attributes of the current message, if available.

Return type

Optional[StatusAttribute]

verify()[source]

Verify the validity of message.

Raises

AssertionError – when the message is not valid

class ehforwarderbot.message.MessageAttribute[source]

Bases: abc.ABC

Abstract class of a message attribute.

class ehforwarderbot.message.LinkAttribute(title, description=None, image=None, url='')[source]

Bases: ehforwarderbot.message.MessageAttribute

Attributes for link messages.

title

Title of the link.

Type

str

description

Description of the link.

Type

str, optional

image

Image/thumbnail URL of the link.

Type

str, optional

url

URL of the link.

Type

str

__init__(title, description=None, image=None, url='')[source]
Parameters
  • title (str) – Title of the link.

  • description (str, optional) – Description of the link.

  • image (str, optional) – Image/thumbnail URL of the link.

  • url (str) – URL of the link.

class ehforwarderbot.message.LocationAttribute(latitude, longitude)[source]

Bases: ehforwarderbot.message.MessageAttribute

Attributes for location messages.

latitude

Latitude of the location.

Type

float

longitude

Longitude of the location.

Type

float

__init__(latitude, longitude)[source]
Parameters
  • latitude (float) – Latitude of the location.

  • longitude (float) – Longitude of the location.

class ehforwarderbot.message.MessageCommand(name, callable_name, args=None, kwargs=None)[source]

Bases: object

A message command.

This object records a way to call a method in the module object. In case where the message has an author from a different module from the chat, this function MUST be called on the author’s module.

The method specified MUST return either a str as result or None if this message will be edited or deleted for further interactions.

name

Human-friendly name of the command.

Type

str

callable_name

Callable name of the command.

Type

str

args

Arguments passed to the function.

Type

Collection[Any]

kwargs

Keyword arguments passed to the function.

Type

Mapping[str, Any]

__init__(name, callable_name, args=None, kwargs=None)[source]
Parameters
  • name (str) – Human-friendly name of the command.

  • callable_name (str) – Callable name of the command.

  • args (Optional[Collection[Any]]) – Arguments passed to the function. Defaulted to empty list;

  • kwargs (Optional[Mapping[str, Any]]) – Keyword arguments passed to the function. Defaulted to empty dict.

class ehforwarderbot.message.MessageCommands(commands)[source]

Bases: list, typing.Generic

Message commands.

Message commands allow user to take action to a specific message, including vote, add friends, etc.

commands

Commands for the message.

Type

list of MessageCommand

__init__(commands)[source]
Parameters

commands (list of MessageCommand) – Commands for the message.

class ehforwarderbot.message.StatusAttribute(status_type, timeout=5000)[source]

Bases: ehforwarderbot.message.MessageAttribute

Attributes for status messages.

Message with type Status notifies the other end to update a chat-specific status, such as typing, send files, etc.

status_type

Type of status, possible values are defined in the StatusAttribute.

timeout

Number of milliseconds for this status to expire. Default to 5 seconds.

Type

Optional[int]

Types[source]

List of status types supported

class Types[source]

Bases: enum.Enum

TYPING

Used in status_type, represent the status of typing.

UPLOADING_FILE

Used in status_type, represent the status of uploading file.

UPLOADING_IMAGE

Used in status_type, represent the status of uploading image.

UPLOADING_VOICE

Used in status_type, represent the status of uploading voice.

UPLOADING_VIDEO

Used in status_type, represent the status of uploading video.

__init__(status_type, timeout=5000)[source]
Parameters
  • status_type (Types) – Type of status.

  • timeout (Optional[int]) – Number of milliseconds for this status to expire. Default to 5 seconds.

class ehforwarderbot.message.Substitutions(substitutions)[source]

Bases: dict, typing.Generic

Message text substitutions, or “@-references”.

This is for the case when user “@-referred” a list of users in the message. Substitutions here is a dict of correspondence between the index of substring used to refer to a user/chat in the message and the chat object it referred to.

Values of the dictionary MUST be either a member of the chat (self or the other for private chats, group members for group chats) or another chat of the slave channel.

A key in this dictionary is a tuple of two ints, where first of it is the starting position in the string, and the second is the ending position defined similar to Python’s substring. A tuple of (3, 15) corresponds to msg.text[3:15]. The value of the tuple (a, b) MUST satisfy \(0 ≤ a < b ≤ l\), where \(l\) is the length of the message text.

Type:

Dict[Tuple[int, int], Chat]

property is_mentioned

Returns True if you are mentioned in this message.

In the case where a chat (private or group) is mentioned in this message instead of a group member, you will also be considered mentioned if you are a member of the chat.

Return type

bool

Examples

Initialization and marking chats

  1. A message delivered from slave channel to master channel

    message = Message(
        deliver_to=master,
        chat=wonderland,
        author=wonderland_alice,
        # More attributes go here...
    )
    
  2. A message delivered from master channel to slave channel

    message = Message(
        deliver_to=slave,
        chat=alice,
        author=alice.self,
        # More attributes go here...
    )
    

Quoting a previous message (targeted message)

Data of the quoted message SHOULD be retrieved from recorded historical data. Message.deliver_to is not required for quoted message, and complete data is not required here. For details, see Message.target.

You MAY use the Channel.get_message() method to get the message object from the sending channel, but this might not always be possible depending on the implementation of the channel.

message.target = Message(
    chat=alice,
    author=alice.other,
    text="Hello, world.",
    type=MsgType.Text,
    uid=MessageID("100000002")
)

Edit a previously sent message

Message ID MUST be the ID from the slave channel regardless of where the message is delivered to.

message.edit = True
message.uid = MessageID("100000003")

Type-specific Information

  1. Text message

    message.type = MsgType.Text
    message.text = "Hello, Wonderland."
    
  2. Media message

    Information related to media processing is described in Media processing.

    The example below is for image (picture) messages. Audio, file, video, sticker works in the same way.

    In non-text messages, the text attribute MAY be an empty string.

    message.type = MsgType.Image
    message.text = "Image caption"
    message.file = NamedTemporaryFile(suffix=".png")
    message.file.write(binary_data)
    message.file.seek(0)
    message.filename = "holiday photo.png"
    message.mime = "image/png"
    
  3. Location message

    In non-text messages, the text attribute MAY be an empty string.

    message.type = MsgType.Location
    message.text = "I'm here! Come and find me!"
    message.attributes = LocationAttribute(51.4826, -0.0077)
    
  4. Link message

    In non-text messages, the text attribute MAY be an empty string.

    message.type = MsgType.Link
    message.text = "Check it out!"
    message.attributes = LinkAttribute(
        title="Example Domain",
        description="This domain is established to be used for illustrative examples in documents.",
        image="https://example.com/thumbnail.png",
        url="https://example.com"
    )
    
  5. Status

    In status messages, the text attribute is disregarded.

    message.type = MsgType.Status
    message.attributes = StatusAttribute(StatusAttribute.TYPING)
    
  6. Unsupported message

    text attribute is required for this type of message.

    message.type = MsgType.Unsupported
    message.text = "Alice requested USD 10.00 from you. "
                   "Please continue with your Bazinga App."
    

Additional information

  1. Substitution

    @-reference the User Themself, another member in the same chat, and the entire chat in the message text.

    message.text = "Hey @david, @bob, and @all. Attention!"
    message.substitutions = Substitutions({
        # text[4:10] == "@david", here David is the user.
        (4, 10): wonderland.self,
        # text[12:16] == "@bob", Bob is another member of the chat.
        (12, 16): wonderland.get_member("bob"),
        # text[22:26] == "@all", this calls the entire group chat, hence the
        # chat object is set as the following value instead.
        (22, 26): wonderland
    })
    
  2. Commands

    message.text = "Carol sent you a friend request."
    message.commands = MessageCommands([
        EFBCommand(name="Accept", callable_name="accept_friend_request",
                   kwargs={"username": "carol_jhonos", "hash": "2a9329bd93f"}),
        EFBCommand(name="Decline", callable_name="decline_friend_request",
                   kwargs={"username": "carol_jhonos", "hash": "2a9329bd93f"})
    ])