Channel

class ehforwarderbot.channel.Channel(instance_id=None)[fuente]

The abstract channel class.

channel_name

A human-friendly name of the channel.

Type

str

channel_emoji

Emoji icon of the channel. Recommended to use a visually-length-one (i.e. a single grapheme cluster) emoji or other symbol that represents the channel best.

Type

str

channel_id

Unique identifier of the channel. Convention of IDs is specified in Empaque y Publicación. This ID will be appended with its instance ID when available.

Type

ModuleID (str)

instance_id

The instance ID if available.

Type

str

__init__(instance_id=None)[fuente]

Initialize the channel. Inherited initializer MUST call the «super init» method at the beginning.

Parámetros

instance_id (Optional[NewType()(InstanceID, str)]) – Instance ID of the channel.

get_message_by_id(chat, msg_id)[fuente]

Get message entity by its ID. Applicable to both master channels and slave channels. Return None when message not found.

Override this method and raise EFBOperationNotSupported if it is not feasible to perform this for your platform.

Parámetros
  • chat (Chat) – Chat in slave channel / middleware.

  • msg_id (NewType()(MessageID, str)) – ID of message from the chat in slave channel / middleware.

Tipo del valor devuelto

Optional[Message]

abstract poll()[fuente]

Method to poll for messages. This method is called when the framework is initialized. This method SHOULD be blocking.

abstract send_message(msg)[fuente]

Process a message that is sent to, or edited in this channel.

Notas

Master channel MUST take care of the returned object that contains the updated message ID. Depends on the implementation of slave channels, the message ID MAY change even after being edited. The old message ID MAY be disregarded for the new one.

Parámetros

msg (Message) – Message object to be processed.

Devuelve

The same message object. Message ID of the object MAY be changed by the slave channel once sent. This can happen even when the message sent is an edited message.

Tipo del valor devuelto

Message

Muestra
  • EFBChatNotFound – Raised when a chat required is not found.

  • EFBMessageTypeNotSupported – Raised when the message type sent is not supported by the channel.

  • EFBOperationNotSupported – Raised when an message edit request is sent, but not supported by the channel.

  • EFBMessageNotFound – Raised when an existing message indicated is not found. E.g.: The message to be edited, the message referred in the msg.target attribute.

  • EFBMessageError – Raised when other error occurred while sending or editing the message.

abstract send_status(status)[fuente]

Process a status that is sent to this channel.

Parámetros

status (Status) – the status object.

Muestra

Nota

Exceptions SHOULD NOT be raised from this method by master channels as it would be hard for a slave channel to process the exception.

This method is not applicable to Slave Channels.

stop_polling()[fuente]

When EFB framework is asked to stop gracefully, this method is called to each channel object to stop all processes in the channel, save all status if necessary, and terminate polling.

When the channel is ready to stop, the polling function MUST stop blocking. EFB framework will quit completely when all polling threads end.

class ehforwarderbot.channel.MasterChannel(instance_id=None)[fuente]

The abstract master channel class. All master channels MUST inherit this class.

class ehforwarderbot.channel.SlaveChannel(instance_id=None)[fuente]

The abstract slave channel class. All slave channels MUST inherit this class.

supported_message_types

Types of messages that the slave channel accepts as incoming messages. Master channels may use this value to decide what type of messages to send to your slave channel.

Leaving this empty may cause the master channel to refuse sending anything to your slave channel.

Type

Set[MsgType]

suggested_reactions

A list of suggested reactions to be applied to messages.

Reactions SHOULD be ordered in a meaningful way, e.g., the order used by the IM platform, or frequency of usage. Note that it is not necessary to list all suggested reactions if that is too long, or not feasible.

Set to None when it is known that no reaction is supported to ANY message in the channel. Set to empty list when it is not feasible to provide a list of suggested reactions, for example, the list of reactions is different for each chat or message.

Type

Optional[Sequence[str]]

abstract get_chat(chat_uid)[fuente]

Get the chat object from a slave channel.

Parámetros

chat_uid (NewType()(ChatID, str)) – ID of the chat.

Devuelve

The chat found.

Tipo del valor devuelto

.Chat

Muestra

EFBChatNotFound – Raised when a chat required is not found.

abstract get_chat_picture(chat)[fuente]

Get the profile picture of a chat. Profile picture is also referred as profile photo, avatar, «head image» sometimes.

Parámetros

chat (.Chat) – Chat to get picture from.

Devuelve

Opened temporary file object. The file object MUST have appropriate extension name that matches to the format of picture sent, and seek to position 0.

It MAY be deleted or discarded once closed, if not needed otherwise.

Tipo del valor devuelto

BinaryIO

Muestra

Ejemplos

if chat.channel_uid != self.channel_uid:
    raise EFBChannelNotFound()
file = tempfile.NamedTemporaryFile(suffix=".png")
response = requests.post("https://api.example.com/get_profile_picture/png",
                         data={"uid": chat.uid})
if response.status_code == 404:
    raise EFBChatNotFound()
file.write(response.content)
file.seek(0)
return file
abstract get_chats()[fuente]

Return a list of available chats in the channel.

Devuelve

a list of available chats in the channel.

Tipo del valor devuelto

Collection[Chat]

get_extra_functions()[fuente]

Get a list of additional features

Tipo del valor devuelto

Dict[NewType()(ExtraCommandName, str), Callable]

Devuelve

A dict of methods marked as additional features. Method can be called with get_extra_functions()["methodName"]().

Operaciones comunes

Enviando mensajes y estados

Sending messages and statuses to other channels is the most common operation of a channel. When enough information is gathered from external sources, the channel would then further process and pack them into the relevant objects, i.e. Message and Status.

When the object is built, the channel should sent it to the coordinator for following steps.

For now, both Message and Status has an attribute that indicates that where this object would be delivered to (deliver_to and destination_channel). This is used by the coordinator when delivering the message.

Messages MUST be sent using coordinator.send_message(). Statuses MUST be sent using coordinator.send_status().

When the object is passed onto the coordinator, it will be further processed by the middleware and then to its destination.

For example, to send a message to the master channel

def on_message(self, data: Dict[str, Any]):
    """Callback when a message is received by the slave channel from
    the IM platform.
    """
    # Prepare message content ...
    message = coordinator.send_message(Message(
        chat=chat,
        author=author,
        type=message_type,
        text=text,
        # more details ...
        uid=data['uid'],
        deliver_to=coordinator.master
    ))
    # Post-processing ...

Acerca del ID del canal

Con la introducción de los ID de las instancias, es necesario utilizar self.channel_id o un equivalente en vez de escribir manualmente el código del ID o utilizar constantes al momento de referirnos al canal ( Ejemplo: al obtener la ruta del archivo de configuración, al crear objetos de mensajes o chats, etc).