Enviar e receber mensagens

Com o LXMF, seu programa vira um contato na rede. Qualquer membro pode escrever para ele pelo MeshChat, pelo Sideband ou pelo NomadNet.

Um robô que responde

import os
import time

import LXMF
import RNS

CONFIG = os.path.expanduser("~/.reticulum-dev")
STORAGE = os.path.expanduser("~/.meu-robo")

os.makedirs(STORAGE, exist_ok=True)
RNS.Reticulum(CONFIG)

identity_path = os.path.join(STORAGE, "identity")
if os.path.exists(identity_path):
    identity = RNS.Identity.from_file(identity_path)
else:
    identity = RNS.Identity()
    identity.to_file(identity_path)

router = LXMF.LXMRouter(identity=identity, storagepath=STORAGE)
me = router.register_delivery_identity(identity, display_name="Meu robô")


def enviar(dest_hash, texto):
    dest = RNS.Destination(
        RNS.Identity.recall(dest_hash),
        RNS.Destination.OUT,
        RNS.Destination.SINGLE,
        "lxmf",
        "delivery",
    )
    msg = LXMF.LXMessage(dest, me, texto, desired_method=LXMF.LXMessage.DIRECT)
    router.handle_outbound(msg)


def recebida(msg):
    texto = msg.content_as_string()
    print("Recebi:", texto)
    enviar(msg.source_hash, f"Você disse: {texto}")


router.register_delivery_callback(recebida)
router.announce(me.hash)
print("Endereço do robô:", RNS.hexrep(me.hash, delimit=False))

while True:
    time.sleep(1)

Pontos de atenção

  • Anuncie. Sem router.announce(...), ninguém encontra o robô.
  • Só responda a quem você conhece. RNS.Identity.recall(...) devolve None se a identidade do remetente ainda não foi aprendida. Peça o caminho antes, com RNS.Transport.request_path(...).
  • Acompanhe a entrega. msg.register_delivery_callback(...) e msg.register_failed_callback(...) avisam o resultado.

Cuidado com laços

Dois robôs que respondem a tudo ficam conversando para sempre. Não responda a mensagens de outros robôs, e limite a frequência de resposta por remetente.