Основні компоненти¶
LXMFBot¶
Головний клас бота, який обробляє маршрутизацію повідомлень, обробку команд і керування життєвим циклом бота.
from lxmfy import LXMFBot
bot = LXMFBot(
name="MyBot",
command_prefix="/",
admins=set(),
config_path=None, # типово "config" у робочій теці
reticulum_config_dir=None, # або LXMFY_RETICULUM_CONFIG_DIR / "~/.reticulum"
test_mode=False, # пропускає запуск RNS, для тестів
log_level="INFO", # рівень логера lxmfy, None не чіпає логування
loglevel=None, # рівень логів RNS 0-7, None бере конфіг reticulum
# Announces
announce=600,
announce_immediately=True,
announce_enabled=True,
announce_display_name_file=None, # файл у config_path, що перевизначає
# анонсоване ім'я (типовий файл:
# bot_display_name.txt)
# Захист від спаму
rate_limit=5,
cooldown=60,
max_warnings=3,
warning_timeout=300,
# Коги
cogs_dir="cogs",
cogs_enabled=True,
dynamic_cogs_enabled=True,
external_cogs_enabled=True,
external_cogs_sandbox_enabled=True,
external_cogs_sandbox_type="auto", # "auto", "landlock", "bwrap", "firejail", "none"
external_cogs_timeout=30,
hot_reloading=False,
# Сховище, події, права
storage_type="json", # "json", "sqlite", "msgpack" або "memory"
storage_path="data",
permissions_enabled=False,
first_message_enabled=True,
event_logging_enabled=True,
max_logged_events=1000,
event_middleware_enabled=True,
# Безпека
signature_verification_enabled=False,
require_message_signatures=False,
require_stamps=False, # відхиляє повідомлення з невалідними stamp
request_unknown_identities=False, # запитує ідентичності відправників у мережі
stamp_cost=None, # вхідна вартість stamp, None вимикає
include_tickets=True, # додає ticket відповіді до вихідних
identity_pinning_enabled=False,
landlock_enabled=True,
# Опційні функції
nlp_enabled=False,
nlp_threshold=0.5,
link_support_enabled=False,
lxmf_commands_enabled=True,
# Доставка
message_persistence_enabled=True,
message_queue_size=50,
opportunistic_sending=True,
direct_delivery_retries=3,
propagation_fallback_enabled=True,
propagation_node=None, # хеш вихідного вузла поширення
autopeer_propagation=False, # знаходить вузли поширення з announces
autopeer_maxdepth=4, # макс. глибина hops для автопірингу, None = без межі
enable_propagation_node=False, # запускає цього бота як вузол поширення
message_storage_limit_mb=500, # ліміт сховища вузла, лише в режимі вузла
# Відкладені відправлення
pending_sends_enabled=True, # тримає відправлення для невідомих адресатів
pending_sends_max=200,
pending_sends_ttl=604800, # 7 днів
pending_sends_retry=300, # секунди між проходами повторів
# RRC
rrc_enabled=False,
rrc_hubs=[],
rrc_rooms=[],
rrc_nick=None,
rrc_dest_name="rrc.hub",
rrc_auto_reconnect=True,
rrc_persist_sessions=True,
)
Усі ці опції є полями BotConfig. LXMFBot(**kwargs) передає кожен
іменований аргумент, тож bot.config містить результуючі значення.
Ключові методи¶
run(delay=10): Запускає головний цикл ботаcleanup(): Персистить черги, скасовує розмови та зупиняє планувальник, роутер і RNS. Викликається автоматично при виході зrun().send(destination, message, title="Reply", lxmf_fields=None, stamp_cost=None, opportunistic=None, method=None, include_ticket=None, defer=None, reply_to=None, quote=None, thread=None): Надсилає повідомлення адресату.stamp_costперевизначає вихідну вартість для цього повідомлення,opportunisticперевизначаєopportunistic_sending,include_ticketперевизначаєinclude_tickets, аdeferперевизначаєpending_sends_enabled.reply_to,quoteіthreadвстановлюють поля тредування відповідей.send_with_attachment(destination, message, attachment, title="Reply", stamp_cost=None, opportunistic=None): Надсилає повідомлення з вкладеннямcommand(name, description="No description provided", admin_only=False, permissions=None, usage=None, examples=None, category=None, aliases=None, threaded=False, rate_limit=None): Декоратор для реєстрації команд.permissionsперевизначає бар'єрDefaultPerms(ALLприadmin_only, інакшеUSE_COMMANDS),threadedвиконує callback у робочому потоці,rate_limitобмежує виклики на відправника за вікно cooldown, аusage,examples,category,aliasesживлять систему довідки. Команди підтримують типізовані аргументи з автоматичною конверсією.intent(name, examples): Декоратор для реєстрації обробників NLP-інтентів.nlp.export_model(): Експортує дані навченої NLP-моделі.nlp.import_model(model_data): Імпортує раніше експортовані дані NLP-моделі.request_link(destination_hash, callback=None, app_name="lxmf", *aspects): Запитує RNS-з'єднання до адресата. Дозволяє власніapp_nameіaspects(типово "lxmf" і "delivery").on_link(callback): Реєструє обробник вхідних RNS-з'єднань.load_extension(name): Завантажує модуль розширення cog за назвою (напр. "cogs.utility").reload_extension(name): Перезавантажує модуль розширення cog.add_cog(cog_instance): Додає екземпляр класу cog до бота.remove_cog(cog_name): Видаляє cog за назвою класу.on_first_message(): Декоратор для обробки перших повідомлень від користувачівon_message(): Декоратор для обробки всіх повідомлень (викликається перед обробкою команд)received(function): Реєструє callback, що викликається з контекстом повідомлення для кожного вхідного повідомлення, яке пройшло pipeline без поглинання командою чи інтентомon_reaction(): Декоратор для обробки вхідних реакцій. Обробники отримують(sender, reaction), де reaction несе ключіreaction_to,reaction_emojiіreaction_senderreact(destination, message_hash, reaction): Надсилає реакцію на повідомлення через поле LXMFFIELD_REACTIONvalidate(): Запускає перевірки конфігурації ботаget_landlock_status(): Повертає доступність і стан активації пісочниці Landlock LSM для процесу ботаdiagnose_destination(destination, request_path=False, wait=0.0): Досліджує стан ідентичності та шляху для хеша адресатаdiagnose_connectivity(destination=None, request_path=False, wait=0.0): Виконує повний doctor-звіт і повертає його dict-омget_debugger(): ПовертаєDebugger, прив'язаний до цього ботаset_propagation_node(node_hash): Фіксує вихідний вузол поширенняget_propagation_node_status(): Стан налаштованих, виявлених і поточного вихідного вузлів поширенняset_message_storage_limit(megabytes): Ліміт сховища при роботі як вузол поширенняget_propagation_storage_stats(): Використання сховища вузла або dict із причиною недоступностіconnect_rrc(hub_hash, rooms=None, nick=None, dest_name=None, auto_reconnect=None): Підключається до RRC-хаба як клієнтdisconnect_rrc(hub_hash=None): Відключає одну чи всі сесії RRC-хабівon_rrc(callback=None): Декоратор або реєстрація обробника для подій RRC (handler(event, client, payload))on_delivery_event(callback=None): Підписується на потік подій вихідної доставки, як декоратор або прямий виклик
Атрибути¶
config: РезультуючаBotConfigcommands,cogs: Реєстри команд і когівstorage: Активний backend сховищаscheduler:TaskSchedulerдля cron-подібних задачevents:EventManagerдля обробників подій і dispatchmiddleware:MiddlewareManagerдля middleware командpermissions:PermissionManagerдля ролей і прапорцівspam_protection:SpamProtectionдля обмежень частоти, попереджень і банівsignature_manager: Шар політики підписівnlp: Класифікатор інтентів (матчить лише приnlp_enabled)delivery:DeliveryTracker, потік вихідних подійconversations:ConversationManagerдля питаньmsg.askrrc:RRCManagerдля сесій із кількома хабами,Noneдоки RRC не ввімкнено абоconnect_rrc()не виконаноlocal:RNS.Destinationбота (його LXMF-адреса цеbot.local.hash)
Анонсоване ім'я¶
Ім'я, яке бачать піри, походить із name, але для announces існують
два перевизначення. Якщо задано announce_display_name_file і такий
файл існує в config_path, його вміст перемагає. Інакше читається
bot_display_name.txt у config_path, якщо він є. У будь-якому разі
присвоєння bot.name = "Нове ім'я" ресинхронізує анонсоване ім'я
під час виконання.
Це дає операторам змогу перейменувати бота без зміни коду, а анонсоване ім'я може відрізнятися від внутрішнього імені в конфігурації.
Структуровані команди через поля LXMF¶
Боти можуть отримувати команди, надіслані через FIELD_COMMANDS
(0x09) LXMF, і автоматично відповідати з FIELD_RESULTS (0x0A). Це
вмикає структуровані процеси запит/відповідь поруч із звичайними
текстовими командами.
Вхідні FIELD_COMMANDS розбираються і спрямовуються через той самий
реєстр команд, що й текстові команди, зі спільними перевірками прав,
розбором типізованих аргументів, потоками та middleware.
from lxmfy import LXMFBot, FIELD_COMMANDS, FIELD_RESULTS, pack_result, unpack_commands
bot = LXMFBot(name="FieldBot")
@bot.command(name="status", description="Return bot status")
def status_cmd(ctx):
# ctx.fields містить сирий словник полів LXMF
# ctx.request_id встановлюється автоматично, якщо команда його містила
ctx.reply("Bot is online")
# Надсилання структурованої команди з іншого клієнта LXMF:
# lxm.fields[FIELD_COMMANDS] = {"command": "status", "args": [], "request_id": "abc123"}
# router.handle_outbound(lxm)
# Відповідь бота автоматично містить FIELD_RESULTS з відповіддю та request_id.
Щоб вимкнути обробку польових команд, задайте
lxmf_commands_enabled=False у BotConfig.
Реакції¶
Реакції передаються як поле LXMF FIELD_REACTION (0x40) на інакше
порожньому повідомленні. pack_reaction і unpack_reaction будують і
розбирають це поле.
from lxmfy import pack_reaction, unpack_reaction
# Надіслати реакцію на повідомлення
bot.react(destination_hash, message_hash_hex, "thumbs up emoji")
# Отримувати реакції
@bot.on_reaction()
def on_reaction(sender, reaction):
# reaction["reaction_to"] - hex-хеш цільового повідомлення
# reaction["reaction_emoji"] - текст реакції (до 16 символів)
# reaction["reaction_sender"] - відправник
print(f"{sender} reacted {reaction['reaction_emoji']} to {reaction['reaction_to']}")
return True
Текст реакції обмежений 16 друкованими символами. Сире поле лишається
доступним у ctx.fields і msg.fields для сумісності.
Тредування відповідей¶
Відповіді можуть нести поля LXMF FIELD_REPLY_TO (0x30),
FIELD_REPLY_QUOTE (0x31) і FIELD_THREAD (0x08). Клієнти, що
рендерять треди, як-от MeshChatX і Sideband, показують їх як справжні
цитовані відповіді замість пласких повідомлень.
msg.reply() тредить автоматично: встановлює FIELD_REPLY_TO на хеш
вхідного повідомлення і FIELD_THREAD на корінь розмови.
@bot.command("status")
def status(msg):
msg.reply("all systems nominal") # тредована відповідь
msg.reply("flat", reply_to=None) # відмовитись від тредування
msg.reply("noted", quote=True) # цитує вхідний текст
Для відправлень, які не є відповідями, передайте поля явно:
Вхідні відповіді парсяться в контекст повідомлення:
@bot.command("ctx")
def ctx_cmd(msg):
msg.reply_to # hex-хеш, на який відповідає це повідомлення, або None
msg.reply_quote # цитований текст відповіді, або None
msg.thread # hex-хеш кореня треду, або None
pack_reply(message_hash, quote=..., thread=...) і
unpack_reply(fields) експортуються для ручної обробки полів.
Розмови¶
Команди можуть ставити відправнику питання і трактувати його наступне повідомлення як відповідь, замість диспетчеризації як команди:
@bot.command("report")
def report(msg):
title = msg.ask("Report title?", timeout=300)
if title is None:
msg.reply("Timed out.")
return
body = msg.ask("Describe the issue.", timeout=600)
if body is None:
msg.reply("Timed out.")
return
msg.reply(f"Filed: {title.content}")
msg.ask(prompt, timeout=..., validator=...) блокує обробник, доки не
надійде відповідь, не спрацює timeout або розмову не буде скасовано.
Повертає Answer із content, fields, hash, sender і шорткатом
reply(text).
Валідатор відхиляє погані відповіді й перепитує:
num = msg.ask(
"Pick a number",
validator=lambda a: None if a.content.isdigit() else "Digits only",
)
В асинхронних обробниках команд використовуйте await
msg.ask_async(...). Для довгих очікувань або коли може бути багато
відкритих розмов, використовуйте стиль колбеків, щоб жоден потік не
залишався припаркованим:
msg.ask(
"Send the log file",
on_answer=lambda ans: ans.reply("received"),
on_timeout=lambda sender: bot.send(sender, "Too slow."),
timeout=3600,
)
Нотатки:
- Надсилання зареєстрованої команди під час очікування питання скасовує питання й виконує команду. Користувачі завжди мають вихід.
bot.conversations.pending_count()іbot.conversations.cancel(sender)відкривають реєстр для діагностики й адміністративних інструментів.- Реєстр обмежений 1024 очікуючими питаннями.
askповертаєNone, коли він заповнений. - Блокуючий
askпаркує потік доставки, що обробляє це повідомлення. Це безпечно для прямих доставок, але боти, що синхронізують великі пакети з вузла поширення, мають надавати перевагу колбекамon_answer.
Сховище¶
Фреймворк надає три бекенди сховища:
JSONStorage¶
SQLiteStorage¶
MsgPackStorage¶
MemoryStorage¶
Команди¶
Реєстрація та обробка команд:
@bot.command(name="hello", description="Says hello")
def hello(ctx):
ctx.reply(f"Hello {ctx.sender}!")
Метадані довідки та контроль доступу надходять із додаткових kwarg-ів декоратора:
from lxmfy import DefaultPerms
@bot.command(
name="purge",
description="Clear stored data",
permissions=DefaultPerms.MANAGE_MESSAGES,
usage="/purge <key>",
examples=["/purge cache"],
category="Admin",
aliases=["clear"],
)
def purge(ctx, key: str):
bot.storage.delete(key)
ctx.reply(f"Deleted {key}")
permissions перевизначає типовий бар'єр: USE_COMMANDS для звичайних
команд, ALL для admin_only. category групує команду у виводі
/help. aliases є лише метаданими довідки: аліаси показуються
користувачам, але не реєструються для dispatch, тож /clear не
виконає purge, хіба що ви зареєструєте його як другу команду.
Типізовані аргументи¶
Команди автоматично розбирають і перетворюють аргументи на основі анотацій типів у функції зворотного виклику.
@bot.command(name="add", description="Adds two numbers")
def add(ctx, a: int, b: int):
result = a + b
ctx.reply(f"The result is {result}")
Обмеження частоти для окремої команди¶
Обмежує, як часто один відправник може викликати команду в межах
глобального вікна cooldown. При досягненні відхиляється лише виклик,
жодних попереджень чи банів.
@bot.command(name="report", rate_limit=3)
def report(ctx):
# кожен відправник може викликати це 3 рази за період cooldown
...
Потребує permissions_enabled=True, як і глобальне обмеження.
Користувачі з роллю admin або BYPASS_SPAM пропускають перевірку.
Захист від спаму¶
bot.spam_protection забезпечує глобальне обмеження: відправник може
надіслати rate_limit повідомлень у межах кожного вікна cooldown.
Перевищення додає попередження і відхиляє повідомлення. На
max_warnings відправника банять. Попередження зникають після
warning_timeout секунд без порушень.
Перевірки спаму виконуються всередині події message_received і
потребують permissions_enabled=True.
bot = LXMFBot(
name="GuardedBot",
permissions_enabled=True,
rate_limit=5, # повідомлень за вікно cooldown
cooldown=60, # тривалість вікна в секундах
max_warnings=3, # попереджень перед баном
warning_timeout=300, # секунд до скидання попереджень
)
# Зняти бан вручну
bot.spam_protection.unban(sender_hash)
Попередження, бани й лічильники персистять у налаштованому backend
сховища, тож бани переживають рестарти. Відправники з BYPASS_SPAM
ніколи не обмежуються й не баняться. Покомандне rate_limit у
@bot.command м'якше: воно лише відхиляє виклик і ніколи не попереджає
чи не банить.
Система довідки¶
Фреймворк включає інтерактивний генератор довідки, який створює категоризовані меню довідки на основі метаданих коґів і команд.
# Команда help реєструється автоматично.
# Користувачі можуть використовувати '/help' або '/help <command>'
Команди в окремому потоці¶
Для довготривалих або блокуючих операцій, які не взаємодіють із Reticulum Network Stack напряму, ви можете виконувати команди в окремому потоці, щоб бот лишався чутливим.
import time
@bot.command(name="long_task", description="Performs a long-running task in a separate thread", threaded=True)
def long_task_command(ctx):
ctx.reply("Starting a long task... please wait.")
time.sleep(10) # Це виконується в окремому потоці
ctx.reply("Long task completed!")
Безпека потоків
Функції, позначені threaded=True, не повинні напряму
взаємодіяти з Reticulum Network Stack (RNS) або будь-якими
компонентами, які покладаються на lxmfy.transport.py, оскільки
вони загалом не є потокобезпечними. Використовуйте ctx.reply() для
надсилання повідомлень користувачу зсередини команди в окремому
потоці.
Події¶
Система подій для обробки різних подій бота:
@bot.events.on("message_received", EventPriority.HIGHEST)
def handle_message(event):
# event.data несе навантаження, напр. sender і message
event.cancel() # зупиняє наступних обробників і подальшу обробку
Обробники виконуються в порядку EventPriority: HIGHEST, HIGH,
NORMAL, LOW. Сама перевірка спаму є обробником message_received
з HIGHEST, тож скасування цієї події є механізмом, яким обмежувач
відкидає повідомлення.
Диспетчеризуйте власні події:
event_logging_enabled, max_logged_events і
event_middleware_enabled існують у BotConfig, але не підключені:
події не записуються у сховище, а bot.events.use() є stub.
Вважайте їх зарезервованими.
Тестування¶
lxmfy.testing.TestBot є LXMFBot, попередньо налаштований для
тестів. Жоден екземпляр Reticulum не запускається. Вхідні повідомлення
проходять справжній pipeline отримання (middleware, перевірки спаму,
права, dispatch), а вихідні відправлення захоплюються для
тверджень.
from lxmfy import TestBot
def test_ping():
with TestBot() as bot:
@bot.command("ping")
def ping(msg):
msg.reply("pong")
sent = bot.receive("/ping", sender="alice")
assert sent[0].content == "pong"
assert sent[0].destination == bot.sender_hex("alice")
bot.receive(content, sender=..., fields=..., message_hash=...)вводить повідомлення і повертає створені об'єктиSentMessage. Відправники іменовані:"alice"мапиться на стабільний фейковий хеш, або передайте hex-хеш адресата напряму.bot.drain()витягує вихідні повідомлення з черги.bot.outboxнакопичує все надіслане.bot.last_sent(sender=...)дістає останнє.bot.wait_sent(n, timeout=...)чекає на потокові команди.bot.receive_later(content, sender=..., delay=...)відповідає на блокуючі викликиmsg.askз daemon-потоку.fake_message(content, source_hash=..., ...)будує вхідне повідомлення для прямого викликуbot._message_received.
SentMessage обгортає кожне захоплене вихідне повідомлення:
destination (hex), content, title, fields, method,
include_ticket, stamp_cost і raw для базового об'єкта.
Тестовий набір репозиторію також містить сценарії надійності та стресу. Запускайте їх тестовим раннером репозиторію.
Розширений набір перевірок надійності¶
Фреймворк включає великий набір автоматизованих тестів для суворих умов:
- Manifold Testing: перевіряє математичну топологію векторного простору NLP-інтентів.
- Chaos Engineering: імітує bit-rot, відмову SD-карти та пошкодження сховища.
- Temporal Drift: перевіряє стійкість до стрибків системного годинника (±1 рік).
- Leak Detection: довготермінове відстеження пам'яті, файлових дескрипторів і потоків.
Права доступу¶
Система прав для керування доступом до функцій бота:
from lxmfy import DefaultPerms
@bot.command(name="admin", description="Admin command", admin_only=True)
def admin_command(ctx):
if ctx.is_admin:
ctx.reply("Admin command executed")
Увімкніть через permissions_enabled=True. Прапорці
DefaultPerms:
USE_BOT,SEND_MESSAGES,USE_COMMANDS: базовий доступMANAGE_MESSAGES,MANAGE_COMMANDS,MANAGE_USERS: підвищенийBYPASS_RATELIMIT,BYPASS_SPAM,VIEW_ADMIN_COMMANDS: спеціальніVIEW_EVENTS,MANAGE_EVENTS,BYPASS_EVENT_CHECKS: система подійNONE,ALL: шорткати
bot.permissions керує ролями та призначеннями:
bot.permissions.create_role("moderator", DefaultPerms.MANAGE_MESSAGES | DefaultPerms.BYPASS_SPAM)
bot.permissions.assign_role(user_hash, "moderator")
bot.permissions.remove_role(user_hash, "moderator")
bot.permissions.has_permission(user_hash, DefaultPerms.USE_COMMANDS)
Ролі та призначення персистять у налаштованому backend сховища.
Існують дві вбудовані ролі, які не можна видалити: user (типова) і
admin, що автоматично надається кожному хешу в admins.
Middleware¶
Система middleware для обробки повідомлень і подій:
from lxmfy import MiddlewareType
@bot.middleware.register(MiddlewareType.PRE_COMMAND)
def pre_command_middleware(ctx):
# ctx обгортає контекст повідомлення, ctx.cancelled відкидає його
if "spamword" in ctx.data.content:
ctx.cancel()
Три точки pipeline виконують middleware:
PRE_COMMAND: перед dispatch команд, після перевірок спаму. Якщо ланцюг повертаєNone, повідомлення повністю скасовується.POST_COMMAND: після callback команди (включно з потоковими командами, які спрацьовують у робочому потоці).PRE_EVENT: перед dispatch подіїmessage_received.
POST_EVENT, REQUEST і RESPONSE існують у MiddlewareType, але
ніщо в pipeline їх поки не виконує.
Вкладення¶
Підтримка надсилання файлів, зображень і аудіо:
from lxmfy import Attachment, AttachmentType
attachment = Attachment(
type=AttachmentType.IMAGE,
name="image.jpg",
data=image_data,
format="jpg"
)
bot.send_with_attachment(destination, "Here's an image", attachment)
Вигляд іконки (поле LXMF)¶
Ви можете задати власну іконку для бота, яку сумісні клієнти LXMF можуть
відображати. Для цього використовується LXMF.FIELD_ICON_APPEARANCE.
from lxmfy import IconAppearance, pack_icon_appearance_field
import LXMF # Потрібен для LXMF.FIELD_ICON_APPEARANCE
# Визначаємо вигляд іконки
icon_data = IconAppearance(
icon_name="smart_toy", # Ім'я з Material Symbols
fg_color=b'\xFF\xFF\xFF', # Білий передній план (3 байти)
bg_color=b'\x4A\x90\xE2' # Синій фон (3 байти)
)
# Пакуємо у формат поля LXMF
icon_lxmf_field = pack_icon_appearance_field(icon_data)
# Надсилаємо повідомлення з цією іконкою
bot.send(
destination_hash_str,
"Hello from your friendly bot!",
title="Bot Message",
lxmf_fields=icon_lxmf_field
)
# Можна також комбінувати з іншими полями, наприклад з вкладеннями:
# attachment_field = pack_attachment(some_attachment)
# combined_fields = {**icon_lxmf_field, **attachment_field}
# bot.send(destination, "Message with icon and attachment", lxmf_fields=combined_fields)
Планувальник¶
Система планування задач:
@bot.scheduler.schedule(name="daily_task", cron_expr="0 0 * * *")
def daily_task():
# Виконується щодня опівночі
pass
Підписи¶
LXMFy надає параметри конфігурації для вбудованого в LXMF криптографічного підписування та перевірки повідомлень:
from lxmfy import LXMFBot
bot = LXMFBot(
name="SecureBot",
signature_verification_enabled=True, # Увімкнути перевірку підписів
require_message_signatures=False # Встановіть True, щоб відхиляти непідписані повідомлення
)
Обробка підписів
LXMF автоматично виконує все криптографічне підписування та
перевірку за допомогою ідентифікаторів RNS. SignatureManager
LXMFy - це шар конфігурації, який:
- Керує тим, чи застосовувати перевірку підписів
- Визначає політику для непідписаних повідомлень (приймати або відхиляти)
- Інтегрується з системою прав (наприклад, обхід перевірки для довірених користувачів)
Фактичні криптографічні операції виконує LXMF/RNS, а не LXMFy.
Пісочниця Landlock LSM¶
На ядрах Linux з підтримкою Landlock (5.13+) LXMFy може обмежувати доступ до файлової системи для процесу бота і для зовнішніх скриптових коґів.
Пісочниця процесу бота
Коли landlock_enabled=True (типово) і бот не працює в test_mode,
бот викликає apply_landlock_sandbox() під час ініціалізації. Системні
каталоги доступні лише для читання; сховище бота, конфігурація, коґи,
конфігурація Reticulum і тимчасові шляхи лишаються доступними для
запису.
bot = LXMFBot(
name="SecureBot",
landlock_enabled=True,
)
status = bot.get_landlock_status()
# ключі status: landlock_kernel_supported, landlock_requested,
# landlock_auto_enabled, landlock_disabled_by_env, landlock_active
Перевизначення через середовище
LXMFY_LANDLOCK=0: вимкнути Landlock навіть на підтримуваних ядрахLXMFY_LANDLOCK=1: спробувати Landlock на Linux незалежно від автовизначення- не встановлено: слідувати
landlock_enabledі автовизначенню ядра
Пісочниця зовнішніх коґів
Скриптові коґи використовують external_cogs_sandbox_type. У режимі
auto перевага надається Landlock, коли він доступний, бо він не
потребує зовнішніх інструментів. Повний список параметрів пісочниці
див. у посібнику Створення ботів.
Закріплення ідентифікатора¶
LXMFy підтримує опційне закріплення ідентифікатора для запобігання імітації, якщо ідентифікатор ротовано або скомпрометовано. Коли увімкнено, бот "закріплює" LXMF-адресу до першого побаченого публічного ключа.
Методи SignatureManager¶
SignatureManager доступний як bot.signature_manager, коли
signature_verification_enabled=True:
should_verify_message(sender): визначає, чи слід перевіряти повідомлення від даного відправникаhandle_unsigned_message(sender, message_hash): обробляє повідомлення без валідних підписів відповідно до політики
Як працюють підписи LXMF¶
LXMF автоматично підписує всі вихідні повідомлення ідентифікатором RNS
відправника під час операції pack(). Коли повідомлення отримано, LXMF
перевіряє підписи і надає:
message.signature_validated: булеве значення, що вказує, чи валідний підписmessage.unverified_reason: код причини, якщо валідація не вдалася (наприклад,SIGNATURE_INVALID,SOURCE_UNKNOWN)
LXMFy використовує ці вбудовані властивості LXMF для застосування політики підписів вашого бота.
Доставка повідомлень¶
LXMFy надає розширені функції доставки повідомлень, включно з вузлами поширення та автоматичними повторними спробами:
Вузли поширення¶
Надсилайте повідомлення через конкретні вузли поширення для підвищення надійності в мережі Reticulum:
# Налаштуйте вузол поширення один раз на рівні конфігурації/виконання
bot.set_propagation_node("<propagation_node_hash>")
# Надсилання з налаштованою поведінкою доставки
bot.send(
destination_hash,
"Message content"
)
# Хеш вузла поширення має бути валідним вузлом поширення LXMF
# у мережі Reticulum
Вузол також можна задати під час створення через
propagation_node="<hash>", або бот може знаходити вузли сам:
bot = LXMFBot(
name="AutoBot",
autopeer_propagation=True, # вчить вузли з announces
autopeer_maxdepth=4, # ігнорує вузли глибше ніж 4 hops
)
bot.get_propagation_node_status() повідомляє про ручний вузол,
виявлені вузли та вихідний вузол, що зараз використовується.
Автоматичні повторні спроби¶
Налаштуйте автоматичні повторні спроби для невдалих прямих доставок:
bot = LXMFBot(
name="ReliableBot",
direct_delivery_retries=5, # Повторювати пряму доставку до 5 разів
propagation_fallback_enabled=True
)
bot.send(destination_hash, "Important message")
# direct_delivery_retries типово дорівнює 3
# Логіка повторів автоматично обробляє зворотні виклики доставки
Система повторів відстежує спроби доставки для кожного отримувача і автоматично повторює невдалі доставки. Успішні доставки скидають лічильник повторів для цього отримувача.
Відкладені відправлення¶
Відправлення адресату, чию ідентичність вузол ще не чув, зазвичай
одразу провалюється. З pending_sends_enabled (типово) повідомлення
натомість тримається у сховищі, а потім автоматично виштовхується,
коли адресат анонсується або під час періодичного проходу.
bot = LXMFBot(
pending_sends_enabled=True,
pending_sends_max=200, # найстаріші втримані повідомлення випадають понад це
pending_sends_ttl=604800, # втримані повідомлення спливають через 7 днів
pending_sends_retry=300, # секунди між проходами в run()
)
# Перевизначення для окремого відправлення
bot.send(dest, "hold this", defer=True)
bot.send(dest, "send or drop", defer=False)
Втримані відправлення з'являються як held (unknown peers) у
адмінській команді /queue і створюють події deferred у трекері
доставки.
Персистентність повідомлень¶
Вихідні повідомлення можуть зберігатися на диску, щоб гарантувати їх
доставку навіть після перезапуску бота. Персистентність увімкнена
типово. Вихідна черга в пам'яті обмежена (message_queue_size, типово
50) і відкидає найстаріше повідомлення, коли заповнена. Невалідні хеші
отримувачів не відновлюються.
Stamp-и та ticket-и¶
Вартість stamp змушує відправників виконувати proof-of-work перед тим, як їхнє повідомлення буде прийнято, що стримує небажаний трафік. LXMFy відкриває обидва боки механізму.
bot = LXMFBot(
stamp_cost=16, # вимагає цю вхідну вартість stamp
require_stamps=True, # відхиляє повідомлення з невалідними stamp
include_tickets=True, # дозволяє пірам відповідати без генерації stamp
)
stamp_costє вхідною вимогою. Вихідна вартість відправлення усе ще береться з announce піра, хіба що ви передастеstamp_cost=доbot.send().include_tickets(типово True) додає ticket відповіді до вихідних повідомлень, тож пір із вимогою stamp може відповісти без оплати. Перевизначайте для окремого відправлення черезinclude_ticket=.request_unknown_identities=Trueзапитує в мережі ідентичність відправника, коли повідомлення надходить із невідомого джерела, що допомагає перевіркам stamp і підписів розв'язатися замість сліпого провалу.
Контроль під час виконання лежить у розділі «Керування роутером»: set_inbound_stamp_cost,
enforce_stamps, ignore_stamps, generate_ticket та методи
інспекції ticket-ів.
Робота як вузол поширення¶
Бот може водночас бути вузлом поширення LXMF, зберігаючи повідомлення для пірів, що офлайн:
bot = LXMFBot(
enable_propagation_node=True,
message_storage_limit_mb=500,
)
bot.set_message_storage_limit(750)
stats = bot.get_propagation_storage_stats()
get_propagation_node_status() працює для обох ролей: повідомляє про
вихідний вузол, який цей бот використовує, і про те, чи він сам слугує
вузлом. Пов'язані контролі: announce_propagation_node() рекламує
вузол, set_retain_on_node() зберігає доставлені повідомлення на ньому,
а allow_control_identity() / disallow_control_identity() керують
тим, які ідентичності можуть використовувати контрольний канал вузла.
Події доставки¶
bot.delivery записує обмежений потік подій вихідного життєвого циклу,
щоб спостерігати за потоком повідомлень без читання логів. Стадії:
queued, deferred, dispatched, delivered, failed, cancelled,
dropped. Нещодавній хвіст персиститься у сховище і відновлюється при
запуску.
@bot.on_delivery_event()
def watch(event):
print(event["stage"], event.get("destination"), event.get("reason"))
# Або пряма інспекція
recent = bot.delivery.recent(20)
failures = bot.delivery.recent(stage="failed")
to_peer = bot.delivery.recent(destination="aa11bb...")
Кожна подія є dict-ом із ts, stage і опційно destination,
message_id, hash, method, attempts, reason, title.
Адміни отримують команду /delivery [limit], що рендерить ту саму
хронологію в чаті, а lxmfy debug показує підсумок хронології доставки
в перевірках pipeline відправлення.
Вбудовані адміністративні команди¶
Ці команди реєструються автоматично й вимагають, щоб відправник був у
admins, коли права ввімкнено:
| Команда | Дія |
|---|---|
/queue |
Показує вихідну чергу роутера, внутрішню чергу та втримані відправлення |
/cancel <id|all> |
Скасовує очікуючі вихідні повідомлення |
/inbox [cancel <hash|all>] |
Перераховує або скасовує активні вхідні передачі |
/delivery [n] |
Показує останні n подій доставки (типово 15, макс. 50) |
/loadext <name> |
Завантажує розширення cog |
/reloadext <name> |
Перезавантажує завантажене розширення cog |
Керування роутером¶
Тонкі обгортки над базовим LXMRouter для керування відправниками,
ticket-ами, керування вихідною чергою та синхронізації вузла
поширення. Усі приймають хеші адресатів як hex-рядки й повертають
False, коли роутер не працює (наприклад у test_mode).
Керування відправниками (вхідне)
ignore_destination(destination)/unignore_destination(destination)/is_ignored(destination): Відкидає вхідні повідомлення від відправникаallow_destination(destination)/disallow_destination(destination): Керування whitelist, коли роутер працює в режимі allow-listprioritise_destination(destination)/unprioritise_destination(destination): Список пріоритетних відправниківset_inbound_stamp_cost(stamp_cost): Вимагає вартість stamp на вхідних повідомленнях (Noneочищає)enforce_stamps()/ignore_stamps(): Перемикачі вимоги вхідних stamp-ів
Ticket-и
generate_ticket(destination, expiry=None): Видає вхідний stamp-ticket для відправникаget_inbound_tickets(destination): Ticket-и, що утримуються для відправникаget_outbound_ticket(destination)/get_outbound_ticket_expiry(destination)/get_outbound_stamp_cost(destination): Стан вихідного ticket-а, дізнаний з мережі
Вихідна черга
outbound_queue(): Знімок очікуючих вихідних повідомленьget_outbound_progress(lxm_hash): Прогрес доставки для хеша повідомлення абоNonecancel_outbound(message_id): Видаляє повідомлення з черги до доставкиdelivery_link_available(destination): Чи існує активне RNS-з'єднання до адресата
Вхідна черга
has_message(message_hash): Чи вже було доставлено вхідний LXM-хешinbound_count(): Активні вхідні передачі ресурсів у процесіinbound_transfers(): Знімок кожної передачі з хешем, розміром, прогресом і статусомcancel_inbound(resource_hash): Перериває активну вхідну передачуcancel_all_inbound(): Перериває всі активні вхідні передачі, повертає скасовану кількість
Виявлення пірів
Метадані announce для адресатів, яких чув цей вузол:
get_peer_app_data(destination): Сирі байти announced app_dataget_peer_lxmf_data(destination): Декодовані метадані LXMF-announce (display_name,stamp_cost,capabilities) абоNone, коли пір не анонсував валідні дані LXMFget_peer_announce(destination): Повний запис announce з hops, received_at, interface і app_datalist_peer_announces(limit=100): Усі почуті announces, найновіші першими
Поширення
sync_propagation_node(max_messages=None): Тягне повідомлення з налаштованого вузла поширенняcancel_propagation_sync(): Зупиняє поточну синхронізаціюget_propagation_stats(): Стан передачі та ліміти вузла абоNoneset_retain_on_node(retain): Зберігає доставлені повідомлення на вузліannounce_propagation_node(): Анонсує цей вузол як вузол поширенняallow_control_identity(destination)/disallow_control_identity(destination): Whitelist контрольного каналу поширення
Прийом
ingest_lxm_uri(uri): Імпортує повідомлення URIlxm://у вхідну чергу
Діагностика¶
Коли повідомлення не течуть, дебагер перевіряє весь шлях замість вгадування: конфігурацію Reticulum, стан спільного екземпляра, інтерфейси, ідентичність, поведінку announce, конфігурацію доставки та pipeline відправлення.
lxmfy debug # повний doctor-звіт, збережений у файл
lxmfy debug probe <hash> --request-path --wait 30
lxmfy debug send <hash> # відстежує тестове відправлення
lxmfy debug receive # перевіряє готовність прийому
lxmfy debug compare <hash_a> <hash_b>
lxmfy debug tips # виправлення поширених збоїв
Звіти типово редагуються задля приватності: домашні шляхи й хеші
обрізаються. --json видає машиночитаний вивід, -o ФАЙЛ записує
звіт, --no-save пропускає файл, --no-privacy зберігає повні значення
для локального використання, а --no-color або NO_COLOR вимикає
ANSI-вивід.
Ті самі перевірки можна викликати з коду:
report = bot.diagnose_connectivity() # doctor-звіт як dict
probe = bot.diagnose_destination( # дослідження ідентичності та шляху
"<peer_hash>", request_path=True, wait=30,
)
debugger = bot.get_debugger() # повний API
checks = debugger.check_send_pipeline()
verdict = debugger.run_doctor(destination)
lxmfy/debugger.py також експортує самостійний помічник
diagnose_destination(hash, ...) плюс типи звітів CheckResult,
DestinationProbe, DoctorReport і MessageDebugger для власних
інструментів.
Обробники повідомлень¶
LXMFy надає декоратори для обробки різних типів вхідних повідомлень:
Обробник першого повідомлення¶
Обробляє перше повідомлення від кожного користувача:
@bot.on_first_message()
def welcome_user(sender, message):
content = message.content.decode("utf-8")
bot.send(sender, f"Welcome! You said: {content}")
return True # Поверніть True, щоб зупинити подальшу обробку
Загальний обробник повідомлень¶
Обробляє всі вхідні повідомлення до обробки команд:
@bot.on_message()
def handle_all_messages(sender, message):
content = message.content.decode("utf-8").strip()
# Ваша логіка тут
if content.startswith("echo:"):
bot.send(sender, content[5:])
return True # Зупинити подальшу обробку
return False # Продовжити до обробки команд
Обробники повідомлень викликаються в такому порядку: 1. Обробник першого
повідомлення (якщо це перше повідомлення від цього відправника) 2.
Загальні обробники повідомлень (зареєстровані через on_message()) 3.
Обробка команд (якщо повідомлення починається з префікса команди)
Резервний callback¶
bot.received(fn) реєструє callback, що виконується в кінці pipeline
для повідомлень, які ніщо інше не поглинуло: жоден обробник першого
повідомлення, жоден обробник on_message із поверненням True, жодна
відповідна команда чи NLP-інтент. Callback отримує той самий контекст
повідомлення, що й команди, з msg.sender, msg.content,
msg.reply() тощо.
Використовуйте як універсальний обробник для вільного тексту.
Reticulum Relay Chat (RRC)¶
Боти можуть приєднуватися до хабів RRC через
RNS Link з конвертами CBOR. Пакет: lxmfy.rrc.
Параметри BotConfig¶
rrc_enabled(bool, типовоFalse): підключати налаштовані хаби при запускуrrc_hubs(список hex-хешів): хеші отримувачів хабівrrc_rooms(список str): кімнати для автоматичного приєднання після WELCOMErrc_nick(str або None): нікнейм у HELLO і повідомленнях кімнатrrc_dest_name(str, типово"rrc.hub"): ім'я отримувача, використане для побудови адреси хабаrrc_auto_reconnect(bool, типовоTrue): перепідключатися після втрати linkrrc_persist_sessions(bool, типовоTrue): зберігати хаби і кімнати між перезапускамиreticulum_config_dir(str або None): каталог конфігурації Reticulum. Також задається черезLXMFY_RETICULUM_CONFIG_DIR. Використовуйте ту саму конфігурацію, що в MeshChatX (часто~/.reticulum), щоб анонси хаба були видимі.
Приклад¶
from lxmfy import LXMFBot, RRCMessage
bot = LXMFBot(
name="RoomBot",
reticulum_config_dir="~/.reticulum",
rrc_enabled=True,
rrc_hubs=["664fc0e8d2e448658e37bb3f34e6c88f"],
rrc_rooms=["general"],
rrc_nick="RoomBot",
)
@bot.on_rrc
def on_rrc(event, client, payload):
if event == "msg" and isinstance(payload, RRCMessage) and payload.mention:
client.send_message(payload.room, f"Hi {payload.nick}")
# API часу виконання
# bot.connect_rrc(hub_hash, rooms=["general"])
# bot.rrc.send_message("general", "hello")
# bot.rrc.send_notice("general", "notice")
# bot.rrc.send_action("general", "waves")
# bot.rrc.join("ops")
# bot.rrc.part("ops")
# bot.rrc.status()
# bot.disconnect_rrc()
Експортовані типи¶
RRCClient: сесія з одним хабомRRCManager: менеджер кількох хабів (bot.rrc)RRCMessage: корисне навантаження події кімнати (kind,room,text,nick,src,mention, ...)RRC_VERSION: константа версії дротового протоколуDEFAULT_DEST_NAME: Типова назва адресата хаба ("rrc.hub")make_envelope,encode_envelope,decode_envelope,validate_envelope,normalize_room: Помічники wire-формату для інструментів, що говорять із хабами напряму
Поширені події, що передаються обробникам @bot.on_rrc, включають
status, welcome, joined, parted, msg, notice, action,
motd, error і rtt.
Шаблони¶
Фреймворк включає кілька готових до використання шаблонів ботів:
EchoBot¶
Простий echo-бот, який повторює повідомлення:
NoteBot¶
Бот для нотаток зі сховищем JSON:
ReminderBot¶
Бот-нагадувач зі сховищем SQLite:
RRCBot¶
RRC-бот для кімнат, який приєднується до налаштованих хабів і
відповідає на @згадки. Типово використовує хаб
664fc0e8d2e448658e37bb3f34e6c88f, кімнату #general і
~/.reticulum, коли доступний.
from lxmfy.templates import RRCBot
bot = RRCBot(
hubs=["664fc0e8d2e448658e37bb3f34e6c88f"],
rooms=["general"],
nick="RRCBot",
reticulum_config_dir="~/.reticulum",
)
bot.run()
Інструменти CLI¶
Фреймворк надає інструменти командного рядка для керування ботами.
Запуск lxmfy без аргументів відкриває інтерактивне меню.
# Інтерактивний scaffold повного проєкту
lxmfy init mybot # тека проєкту, bot.py, cogs/, README
lxmfy init --here --yes # поточна тека, приймає всі типові значення
# Створити один файл бота
lxmfy create mybot
lxmfy create --template echo mybot
lxmfy create --template rrc my_rrc_bot
lxmfy create mybot --no-cogs # пропускає пакет cogs
lxmfy create --output dir/bot.py --name MyBot
# Запустити бота з шаблону
lxmfy run echo
lxmfy run rrc
lxmfy run reminder --name "MyReminder"
# Діагностувати з'єднання (див. розділ Діагностика)
lxmfy debug
lxmfy debug probe <hash> --request-path --wait 30
# Тестувати перевірку підписів з повідомленням
lxmfy signatures test
# Увімкнути перевірку підписів
lxmfy signatures enable
# Вимкнути перевірку підписів
lxmfy signatures disable
lxmfy init запитує назву проєкту, шаблон, backend сховища, префікс
команд і хеші адмінів. Кожне питання приймає натомість прапорець:
--dir, --bot-name, --template, --storage, --prefix,
--admins, --no-cogs, --force, --yes. На не-TTY stdin беруться
типові значення.
Шаблони для create і run: basic, echo, reminder, note,
cogtest, rrc.
Обробка помилок¶
Перехоплюйте помилки завершення роботи та виконання навколо bot.run():
try:
bot.run()
except KeyboardInterrupt:
bot.cleanup()
except Exception as e:
logger.error(f"Error running bot: {str(e)}")
Довідник модулів¶
Згенеровано з docstring у вихідному коді.
Bases: AnnounceMixin, DispatchMixin, CogMixin, InboundMixin, OutboundMixin, LinkMixin, RRCMixin, PropagationMixin
Main bot class for handling LXMF messages and commands.
This class manages the bot's lifecycle, including: - Message routing and delivery - Command registration and execution - Cog (extension) loading and management - Spam protection - Admin privileges
Source code in lxmfy/core.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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | |
__init__(name=None, **kwargs)
¶
Initialize a new LXMFBot instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Optional bot name, same as the name config key. |
None
|
**kwargs
|
Any
|
Override default configuration settings |
{}
|
Source code in lxmfy/core.py
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
cleanup()
¶
Clean up resources.
Source code in lxmfy/core.py
diagnose_connectivity(destination=None, *, request_path=False, wait=0.0)
¶
Run a connectivity doctor report for this bot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
destination
|
str | None
|
Optional peer hash to include in send diagnosis. |
None
|
request_path
|
bool
|
Request a path when probing destination. |
False
|
wait
|
float
|
Seconds to wait for path discovery. |
0.0
|
Returns:
| Type | Description |
|---|---|
dict
|
Structured doctor report dict. |
Source code in lxmfy/core.py
diagnose_destination(destination, *, request_path=False, wait=0.0)
¶
Probe path and identity for a destination hash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
destination
|
str
|
Hex destination hash. |
required |
request_path
|
bool
|
Whether to request a path if missing. |
False
|
wait
|
float
|
Seconds to wait for a path after requesting. |
0.0
|
Returns:
| Type | Description |
|---|---|
dict
|
Dict describing identity/path status and hints. |
Source code in lxmfy/core.py
get_debugger()
¶
get_landlock_status()
¶
Return Landlock LSM sandbox availability and activation state.
on_delivery_event(callback=None)
¶
Subscribe to the outbound delivery event stream.
Usable as bot.on_delivery_event(fn) or as a decorator @bot.on_delivery_event(). Subscribers receive event dicts with ts, stage (queued, deferred, dispatched, delivered, failed, cancelled, dropped), and destination/message_id/hash/reason fields when available.
Source code in lxmfy/core.py
request_page(destination_hash, page_path, field_data=None)
¶
Request a page from a destination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
destination_hash
|
str
|
The destination hash. |
required |
page_path
|
str
|
The path to the page. |
required |
field_data
|
dict | None
|
Optional field data to send with the request. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
The response from the destination. |
Source code in lxmfy/core.py
run(delay=10)
¶
Run the bot
Source code in lxmfy/core.py
Configuration settings for LXMFBot.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the bot. Defaults to "LXMFBot". |
announce |
int
|
The announce interval in seconds. Defaults to 600. |
announce_immediately |
bool
|
Whether to announce immediately on startup. Defaults to True. |
admins |
set
|
A set of admin identity hashes. Defaults to an empty set. |
hot_reloading |
bool
|
Whether to enable hot reloading of cogs. Defaults to False. |
rate_limit |
int
|
The maximum number of messages allowed per cooldown period. Defaults to 5. |
cooldown |
int
|
The cooldown period in seconds. Defaults to 60. |
max_warnings |
int
|
The maximum number of spam warnings before action is taken. Defaults to 3. |
warning_timeout |
int
|
The duration in seconds for which a spam warning is active. Defaults to 300. |
command_prefix |
str
|
The prefix for bot commands. Defaults to "/". |
cogs_dir |
str
|
The directory to load cogs from. Defaults to "cogs". |
cogs_enabled |
bool
|
Whether to enable cogs. Defaults to True. |
permissions_enabled |
bool
|
Whether to enable the permission system. Defaults to False. |
storage_type |
str
|
The type of storage to use ("json", "sqlite", "msgpack", or "memory"). Defaults to "json". |
storage_path |
str
|
The path to the storage file or directory. Defaults to "data". |
first_message_enabled |
bool
|
Whether to enable first message handling. Defaults to True. |
event_logging_enabled |
bool
|
Whether to enable event logging. Defaults to True. |
max_logged_events |
int
|
The maximum number of events to log. Defaults to 1000. |
event_middleware_enabled |
bool
|
Whether to enable event middleware. Defaults to True. |
announce_enabled |
bool
|
Whether to enable bot announcements. Defaults to True. |
signature_verification_enabled |
bool
|
Whether to enable cryptographic signature verification for incoming messages. Defaults to False. |
require_message_signatures |
bool
|
Whether to reject unsigned messages when signature verification is enabled. Defaults to False. |
require_stamps |
bool
|
Whether to reject messages with invalid stamps. Defaults to False. |
request_unknown_identities |
bool
|
Whether to request unknown identities from the network when a message is received from an unknown source. Defaults to False. |
stamp_cost |
int
|
Stamp cost required for messages to this bot. Outbound cost still comes from the peer announce unless send() overrides it. None disables inbound stamps. Defaults to None. |
include_tickets |
bool
|
Include reply tickets on outbound messages so peers that require stamps can answer without stamp generation. Defaults to True. |
direct_delivery_retries |
int
|
Number of times to retry direct delivery before falling back to propagation. Defaults to 3. |
propagation_fallback_enabled |
bool
|
Whether to use propagation nodes as fallback after direct delivery fails. Defaults to True. |
propagation_node |
str
|
The destination hash of the outbound propagation node. If None and autopeer_propagation is True, automatically discovers nodes. Defaults to None. |
autopeer_propagation |
bool
|
Whether to automatically discover and peer with propagation nodes from announces. Defaults to False. |
autopeer_maxdepth |
int
|
Maximum hop depth for auto-peering with propagation nodes. None = no limit. Defaults to 4. |
enable_propagation_node |
bool
|
Whether to run this bot as a propagation node. Defaults to False. |
message_storage_limit_mb |
float
|
Maximum storage for propagation node messages in megabytes. Only applies when enable_propagation_node is True. Defaults to 500 MB. |
config_path |
str
|
The path to the bot configuration directory. If None, defaults to "config" in the current working directory. Defaults to None. |
reticulum_config_dir |
str
|
The Reticulum config directory used for RNS shared instance/auth state. If None, uses LXMFY_RETICULUM_CONFIG_DIR when set, otherwise discovers the user/system Reticulum config (/etc/reticulum, ~/.config/reticulum, ~/.reticulum), and only then falls back to config_path. Isolated bot configs force share_instance=No to avoid RPC digest rejection with NomadNet/Columba. |
test_mode |
bool
|
Whether to run in test mode (skips RNS initialization). Defaults to False. |
log_level |
str or int or None
|
Logging level for lxmfy's own logger ("DEBUG", "INFO", "WARNING", ...). None leaves logging untouched. Defaults to "INFO". |
loglevel |
int
|
RNS log level (0-7) passed to RNS.Reticulum. None uses the Reticulum config file setting. Defaults to None. |
pending_sends_enabled |
bool
|
Hold outbound messages when the destination identity is not yet known, retrying on announces and periodic sweeps. Defaults to True. |
pending_sends_max |
int
|
Maximum deferred messages kept for unknown destinations. Oldest are dropped beyond this. Defaults to 200. |
pending_sends_ttl |
int
|
Seconds a deferred message is kept before being dropped. Defaults to 604800 (7 days). |
pending_sends_retry |
int
|
Minimum seconds between deferred-send sweeps in run(). Defaults to 300. |
announce_display_name_file |
str
|
Optional filename under config_path whose UTF-8 contents override the bot display name for LXMF delivery announces. If unset, |
Source code in lxmfy/config.py
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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 | |
__post_init__()
¶
Post-initialization to ensure admins is a set.
Source code in lxmfy/config.py
__str__()
¶
Return a string representation of the BotConfig object.
Source code in lxmfy/config.py
A decorator class for bot commands.
This class is used to mark methods as bot commands and provide metadata about the command such as its name, description, and permission requirements.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the command |
description |
str
|
A description of what the command does |
admin_only |
bool
|
Whether the command is restricted to admin users |
callback |
callable
|
The function that implements the command |
Source code in lxmfy/commands.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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 | |
__call__(func)
¶
Decorate a function as a command.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
callable
|
The function to be decorated |
required |
Returns:
| Name | Type | Description |
|---|---|---|
callable |
The decorated function |
__get__(obj, objtype=None)
¶
Support instance methods in command definitions.
This method enables the command decorator to work with instance methods by properly binding the method to the instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
The instance that the command is bound to |
required | |
objtype
|
The type of the instance |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Command |
A new Command instance bound to the object |
Source code in lxmfy/commands.py
__init__(name, description='No description provided', admin_only=False, permissions=None, usage=None, examples=None, category=None, aliases=None, threaded=False, rate_limit=None)
¶
Initialize a new Command.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the command |
required |
description
|
str
|
Description of the command. Defaults to "No description provided" |
'No description provided'
|
admin_only
|
bool
|
Whether the command requires admin privileges. Defaults to False |
False
|
rate_limit
|
int
|
Max invocations per sender per cooldown window for this command. None disables the per-command limit; the global message rate limit still applies. |
None
|
Source code in lxmfy/commands.py
Represents a generic attachment.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
AttachmentType
|
The type of the attachment (AttachmentType). |
name |
str
|
The name of the attachment. |
data |
bytes
|
The binary data of the attachment. |
format |
str | None
|
Optional format specifier (e.g., "png" for images). |
Source code in lxmfy/attachments.py
Bases: IntEnum
Enumerates the different types of attachments supported.
FILE: Represents a generic file attachment. IMAGE: Represents an image attachment. AUDIO: Represents an audio attachment.
Source code in lxmfy/attachments.py
Data class representing an event.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the event. |
data |
dict
|
A dictionary containing event-specific data. |
cancelled |
bool
|
A flag indicating whether the event has been cancelled. |
Source code in lxmfy/events.py
__eq__(other)
¶
Compares this event to another object for equality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
The object to compare to. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if the other object is an Event instance and has the same name, False otherwise. |
Source code in lxmfy/events.py
__hash__()
¶
Returns the hash value of the event based on its name.
Returns:
| Name | Type | Description |
|---|---|---|
int |
Hash value of the event name. |
Manages event registration, dispatching, and logging.
Source code in lxmfy/events.py
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
__init__(storage)
¶
Initializes the EventManager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage
|
The storage object used for logging events. |
required |
dispatch(event)
¶
Dispatches an event to all registered handlers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
Event
|
The event to dispatch. |
required |
Source code in lxmfy/events.py
on(event_name, priority=EventPriority.NORMAL)
¶
Registers an event handler for a specific event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_name
|
str
|
The name of the event to handle. |
required |
priority
|
EventPriority
|
The priority of the event handler (default: EventPriority.NORMAL). |
NORMAL
|
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
A decorator that registers the decorated function as an event handler. |
Source code in lxmfy/events.py
use(middleware)
¶
Adds middleware to the event pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
middleware
|
Callable
|
The middleware function to add. |
required |
Bases: Enum
Enumeration of event priority levels.
Members
HIGHEST: Highest priority. HIGH: High priority. NORMAL: Normal priority. LOW: Low priority.
Source code in lxmfy/events.py
Manages middleware registration and execution
Source code in lxmfy/middleware.py
execute(mw_type, data)
¶
Execute middleware chain for given type
Source code in lxmfy/middleware.py
register(middleware_type, func=None)
¶
Register a middleware function
Source code in lxmfy/middleware.py
Bases: Flag
Default permission set
Source code in lxmfy/permissions.py
Manages permissions, roles, and user assignments
Source code in lxmfy/permissions.py
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
assign_role(user, role_name)
¶
Assign a role to a user
Source code in lxmfy/permissions.py
create_role(name, permissions, priority=0, description=None)
¶
Create a new role
Source code in lxmfy/permissions.py
delete_role(name)
¶
Delete a role
Source code in lxmfy/permissions.py
get_user_permissions(user)
¶
Get combined permissions for a user
Source code in lxmfy/permissions.py
has_permission(user, permission)
¶
Check if user has specific permission
load_data()
¶
Load permission data from storage
Source code in lxmfy/permissions.py
remove_role(user, role_name)
¶
Remove a role from a user
Source code in lxmfy/permissions.py
save_data()
¶
Save permission data to storage
Source code in lxmfy/permissions.py
Default help formatter for commands.
Source code in lxmfy/help.py
format_all_commands(categories)
staticmethod
¶
Format the complete help listing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
categories
|
dict
|
A dictionary where keys are category names and values are lists of command objects. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A formatted string containing help information for all commands. |
Source code in lxmfy/help.py
format_category(category, commands)
staticmethod
¶
Format a category of commands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
|
str
|
The name of the category. |
required |
commands
|
list
|
A list of command objects in the category. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A formatted string containing the category's help information. |
Source code in lxmfy/help.py
format_command(command)
staticmethod
¶
Format a single command's help.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
The command object to format. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A formatted string containing the command's help information. |
Source code in lxmfy/help.py
A system for providing help information about available commands.
Source code in lxmfy/help.py
__init__(bot, formatter=None)
¶
Initialize the HelpSystem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bot
|
LXMFBot
|
The bot instance. |
required |
formatter
|
HelpFormatter | None
|
An optional help formatter. Defaults to HelpFormatter. |
None
|
Source code in lxmfy/help.py
Manages scheduled tasks and background processes.
Source code in lxmfy/scheduler.py
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | |
__init__(bot)
¶
Initialize the TaskScheduler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bot
|
Any
|
The bot instance. |
required |
Source code in lxmfy/scheduler.py
add_task(name, callback, cron_expr)
¶
Add a scheduled task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the task. |
required |
callback
|
Callable
|
The function to execute when the task runs. |
required |
cron_expr
|
str
|
A cron-style expression defining when the task should run. |
required |
Source code in lxmfy/scheduler.py
remove_task(name)
¶
Remove a scheduled task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the task to remove. |
required |
schedule(name, cron_expr)
¶
Decorator to schedule a task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the task. |
required |
cron_expr
|
str
|
The cron expression for the task. |
required |
Source code in lxmfy/scheduler.py
start()
¶
A scheduled task with cron-style timing.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the task. |
callback |
Callable
|
The function to execute when the task runs. |
cron_expr |
str
|
A cron-style expression defining when the task should run (min hour day month weekday). |
last_run |
Optional[datetime]
|
The last time the task was run. |
enabled |
bool
|
Whether the task is currently enabled. |
Source code in lxmfy/scheduler.py
should_run(current_time)
¶
Check if the task should run at the given time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_time
|
datetime
|
The current datetime. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the task should run, False otherwise. |
Source code in lxmfy/scheduler.py
Facade for the underlying storage backend.
Source code in lxmfy/storage.py
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 | |
__init__(backend)
¶
Initialize a new Storage instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
StorageBackend
|
The storage backend to use. |
required |
delete(key)
¶
exists(key)
¶
Check if a key exists in storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the key exists, False otherwise. |
get(key, default=None)
¶
Retrieve a value from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
default
|
Any
|
The default value to return if the key is not found. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The value associated with the key, or the default value if not found. |
Source code in lxmfy/storage.py
get_role_data(role_name)
¶
Helper method for permission system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
role_name
|
str
|
The name of the role. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
The role data. |
get_user_roles(user_hash)
¶
Helper method for permission system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_hash
|
str
|
The hash of the user. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
The list of roles for the user. |
Source code in lxmfy/storage.py
scan(prefix)
¶
Scan for keys with a given prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
The prefix to scan for. |
required |
Returns:
| Type | Description |
|---|---|
list
|
A list of keys that start with the prefix. |
set(key, value)
¶
Store a value in storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to store the value under. |
required |
value
|
Any
|
The value to store. |
required |
set_role_data(role_name, data)
¶
Helper method for permission system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
role_name
|
str
|
The name of the role. |
required |
data
|
dict
|
The role data. |
required |
set_user_roles(user_hash, roles)
¶
Helper method for permission system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_hash
|
str
|
The hash of the user. |
required |
roles
|
list[str]
|
The list of roles for the user. |
required |
Bases: StorageBackend
JSON file-based storage backend.
Source code in lxmfy/storage.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | |
__init__(directory)
¶
Initialize a new JSONStorage instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str
|
The directory to store the JSON files in. |
required |
Source code in lxmfy/storage.py
delete(key)
¶
Delete a value from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to delete. |
required |
Source code in lxmfy/storage.py
exists(key)
¶
Check if a key exists in storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the key exists, False otherwise. |
get(key, default=None)
¶
Retrieve a value from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
default
|
Any
|
The default value to return if the key is not found. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The value associated with the key, or the default value if not found. |
Source code in lxmfy/storage.py
scan(prefix)
¶
Scan for keys with a given prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
The prefix to scan for. |
required |
Returns:
| Type | Description |
|---|---|
list
|
A list of keys that start with the prefix. |
Source code in lxmfy/storage.py
set(key, value)
¶
Store a value in storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to store the value under. |
required |
value
|
Any
|
The value to store. |
required |
Source code in lxmfy/storage.py
Bases: StorageBackend
SQLite database storage backend.
Source code in lxmfy/storage.py
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 | |
__init__(database_path)
¶
Initialize a new SQLiteStorage instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
database_path
|
str
|
The path to the SQLite database file. |
required |
Source code in lxmfy/storage.py
delete(key)
¶
Delete a value from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to delete. |
required |
Source code in lxmfy/storage.py
exists(key)
¶
Check if a key exists in storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the key exists, False otherwise. |
Source code in lxmfy/storage.py
get(key, default=None)
¶
Retrieve a value from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
default
|
Any
|
The default value to return if the key is not found. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The value associated with the key, or the default value if not found. |
Source code in lxmfy/storage.py
scan(prefix)
¶
Scan for keys with a given prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
The prefix to scan for. |
required |
Returns:
| Type | Description |
|---|---|
list
|
A list of keys that start with the prefix. |
Source code in lxmfy/storage.py
set(key, value)
¶
Store a value in storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to store the value under. |
required |
value
|
Any
|
The value to store. |
required |
Source code in lxmfy/storage.py
Bases: StorageBackend
In-memory storage backend.
Source code in lxmfy/storage.py
Bases: StorageBackend
MsgPack file-based storage backend.
Uses the msgpack implementation vendored with RNS
(RNS.vendor.umsgpack), so no extra dependency is needed. Stores
each key in its own {key}.msgpack file, mirroring JSONStorage.
Source code in lxmfy/storage.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | |
__init__(directory)
¶
Initialize a new MsgPackStorage instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str
|
The directory to store the msgpack files in. |
required |
Source code in lxmfy/storage.py
delete(key)
¶
Delete a value from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to delete. |
required |
Source code in lxmfy/storage.py
exists(key)
¶
Check if a key exists in storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the key exists, False otherwise. |
get(key, default=None)
¶
Retrieve a value from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
default
|
Any
|
The default value to return if the key is not found. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The value associated with the key, or the default value if not found. |
Source code in lxmfy/storage.py
scan(prefix)
¶
Scan for keys with a given prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
The prefix to scan for. |
required |
Returns:
| Type | Description |
|---|---|
list
|
A list of keys that start with the prefix. |
Source code in lxmfy/storage.py
set(key, value)
¶
Store a value in storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to store the value under. |
required |
value
|
Any
|
The value to store. |
required |
Source code in lxmfy/storage.py
Tracks pending questions per sender and resolves them on reply.
Source code in lxmfy/conversations.py
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | |
ask(sender, prompt, *, timeout=DEFAULT_TIMEOUT, title=None, validator=None)
¶
Send a prompt and block until the sender replies.
Returns an Answer with content, fields, and hash, or None on
timeout or cancellation. In async command handlers use
await msg.ask_async(...) instead. For long waits prefer the
callback style with on_answer so no thread stays parked.
Source code in lxmfy/conversations.py
ask_async(sender, prompt, *, timeout=DEFAULT_TIMEOUT, title=None, validator=None)
async
¶
Send a prompt and await the sender's reply.
Same contract as ask, for async command handlers.
Source code in lxmfy/conversations.py
ask_callback(sender, prompt, on_answer, *, timeout=DEFAULT_TIMEOUT, title=None, validator=None, on_timeout=None)
¶
Send a prompt and invoke on_answer(answer) when the reply arrives.
Non-blocking. on_timeout(sender) fires if the sender never answers. Returns False when the pending limit is reached.
Source code in lxmfy/conversations.py
cancel(sender)
¶
cancel_all()
¶
has_pending(sender)
¶
pending_count()
¶
pending_senders()
¶
resolve(sender, message)
¶
Feed an inbound message to a pending question.
Returns True when the message was consumed as an answer. When a validator rejects the answer the question stays pending.
Source code in lxmfy/conversations.py
The message that answered a pending question.
Source code in lxmfy/conversations.py
reply(text, **kwargs)
¶
Reply to the sender who answered, threading to their message.
Bounded delivery event stream with subscribers and persistence.
Source code in lxmfy/delivery.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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 | |
__init__(storage=None, maxlen=500)
¶
Initialize the tracker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage
|
Optional Storage facade for persisting the recent tail of the stream. Pass None to keep events in memory. |
None
|
|
maxlen
|
int
|
Maximum in-memory events retained. |
500
|
Source code in lxmfy/delivery.py
load_persisted()
¶
Restore the persisted tail into memory at startup.
Source code in lxmfy/delivery.py
recent(limit=None, *, stage=None, destination=None)
¶
Return the most recent events, oldest first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int | None
|
Maximum events returned, counted from the newest. |
None
|
stage
|
str | None
|
Optional stage filter. |
None
|
destination
|
str | None
|
Optional exact destination filter. |
None
|
Source code in lxmfy/delivery.py
record(stage, **fields)
¶
Append a delivery event and notify subscribers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
str
|
One of STAGES. |
required |
**fields
|
Optional event fields: destination, message_id, hash, method, attempts, reason, title. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The recorded event dict. |
Source code in lxmfy/delivery.py
subscribe(callback)
¶
unsubscribe(callback)
¶
Remove a subscriber. Returns True when it was registered.
Bases: LXMFBot
LXMFBot preconfigured for tests, with message injection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Bot name. |
'TestBot'
|
**overrides
|
Any LXMFBot/BotConfig keyword. Test-friendly defaults apply unless overridden. |
{}
|
Source code in lxmfy/testing.py
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
close()
¶
drain()
¶
Pop all queued outbound messages and append them to outbox.
Source code in lxmfy/testing.py
last_sent(sender=None)
¶
Most recent outbound message, optionally filtered by sender.
Source code in lxmfy/testing.py
receive(content, *, sender='alice', title=None, fields=None, message_hash=None)
¶
Inject an inbound message through the real receive pipeline.
Returns the outbound messages produced while handling it. For threaded commands use wait_sent after receive.
Source code in lxmfy/testing.py
receive_later(content, *, sender='alice', delay=0.05, **kwargs)
¶
Deliver an inbound message on a daemon thread after a delay.
Used to answer blocking msg.ask calls inside command handlers.
Source code in lxmfy/testing.py
sender_hash(sender='alice')
¶
Stable source hash for a named fake sender.
Accepts a name (mapped to a fixed random hash per bot) or a hex destination hash.
Source code in lxmfy/testing.py
sender_hex(sender='alice')
¶
wait_sent(count=1, timeout=5.0)
¶
Wait until at least count new outbound messages are queued.
Source code in lxmfy/testing.py
An outbound message captured from the bot queue.
Source code in lxmfy/testing.py
Diagnose LXMF send/receive connectivity problems.
Source code in lxmfy/debugger.py
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 | |
__init__(*, reticulum_config_dir=None, config_path=None, bot=None, privacy=True)
¶
Create a debugger.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reticulum_config_dir
|
str | None
|
Explicit Reticulum config directory. |
None
|
config_path
|
str | None
|
Bot config directory (identity, announce state). |
None
|
bot
|
Any | None
|
Optional running LXMFBot instance to introspect. |
None
|
privacy
|
bool
|
Redact paths/hashes in reports (default True). |
True
|
Source code in lxmfy/debugger.py
check_announce(*, try_announce=False)
¶
Announce configuration and optional live announce test.
Source code in lxmfy/debugger.py
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 | |
check_bot_identity()
¶
Report bot delivery destination if available.
Source code in lxmfy/debugger.py
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 | |
check_delivery_config()
¶
Report effective delivery knobs (bot config or framework defaults).
Source code in lxmfy/debugger.py
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 | |
check_delivery_timeline(limit=10)
¶
Render recent delivery events from the live bot or disk.
Source code in lxmfy/debugger.py
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 | |
check_disk_permissions()
¶
Verify config, storage, and Reticulum dirs are usable.
Source code in lxmfy/debugger.py
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 | |
check_environment()
¶
OS, Python, and package versions.
Source code in lxmfy/debugger.py
check_instance()
¶
Shared RNS instance vs owned/isolated bot config.
Source code in lxmfy/debugger.py
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 | |
check_interfaces()
¶
Report Reticulum interface status (no hostnames/IPs).
Source code in lxmfy/debugger.py
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 | |
check_send_pipeline()
¶
Internal reasons messages would or would not leave the bot.
Source code in lxmfy/debugger.py
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 | |
check_storage_history()
¶
Read delivery_attempts / persisted_queue from disk without a live bot.
Source code in lxmfy/debugger.py
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 | |
compare_destinations(left, right, *, request_path=False, wait=0.0)
¶
Compare path/identity status for two destination hashes.
Source code in lxmfy/debugger.py
diagnose_receive()
¶
Explain why peers may not be able to reach this bot.
Source code in lxmfy/debugger.py
diagnose_send(destination, *, probe=None)
¶
Explain why sending to a destination may fail.
Source code in lxmfy/debugger.py
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 | |
ensure_reticulum(loglevel=None)
¶
Initialize Reticulum if needed.
Source code in lxmfy/debugger.py
format_report_text(report)
¶
Format a plain-text privacy-friendly report for files/sharing.
Source code in lxmfy/debugger.py
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 | |
print_probe(probe, *, as_json=False)
¶
Print a destination probe result.
Source code in lxmfy/debugger.py
print_report(report, *, as_json=False)
¶
Print a doctor report to the terminal.
Source code in lxmfy/debugger.py
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 | |
probe_destination(destination, *, request_path=False, wait=0.0)
¶
Probe path and identity knowledge for a destination.
Source code in lxmfy/debugger.py
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 | |
run_doctor(destination=None, *, request_path=False, wait=0.0, try_announce=False)
¶
Run a full connectivity doctor report.
Source code in lxmfy/debugger.py
save_report(report, path=None, *, as_json=False)
¶
Write report to a file and return the path used.
Source code in lxmfy/debugger.py
Full connectivity doctor report.
Source code in lxmfy/debugger.py
Path/identity probe for a destination hash.
Source code in lxmfy/debugger.py
Client session for a single RRC hub destination.
Source code in lxmfy/rrc/client.py
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 | |
connected
property
¶
True when the session is welcomed and the link is active.
connect()
¶
Begin connecting to the hub in a background thread.
Source code in lxmfy/rrc/client.py
disconnect()
¶
Tear down the session and cancel reconnect.
Source code in lxmfy/rrc/client.py
join(room, key=None)
¶
Request membership in a room. Returns the normalized room name.
Source code in lxmfy/rrc/client.py
part(room)
¶
Leave a room. Returns the normalized room name.
Source code in lxmfy/rrc/client.py
ping()
¶
Send a PING and return the correlation body.
Source code in lxmfy/rrc/client.py
send_action(room, text)
¶
send_command(text, room=None)
¶
Send a slash command as a MSG body.
Source code in lxmfy/rrc/client.py
send_message(room, text)
¶
send_notice(room, text)
¶
set_auto_join(rooms)
¶
Configure rooms to join automatically after WELCOME.
set_nick(nick)
¶
Set the advisory nickname used on outgoing envelopes.
Source code in lxmfy/rrc/client.py
status_dict()
¶
Return a serializable status snapshot.
Source code in lxmfy/rrc/client.py
Owns RRCClient sessions and fans events out to bot handlers.
Source code in lxmfy/rrc/manager.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | |
connect(hub_hash, rooms=None, nick=None, dest_name=None, auto_reconnect=None)
¶
Connect to an RRC hub. Returns the client session.
Source code in lxmfy/rrc/manager.py
disconnect(hub_hash=None)
¶
Disconnect one hub, or all hubs when hub_hash is None.
Source code in lxmfy/rrc/manager.py
get(hub_hash)
¶
Return a connected client for a hub hash, if present.
Source code in lxmfy/rrc/manager.py
join(room, hub_hash=None)
¶
Join a room on the first connected hub, or a specific hub.
Source code in lxmfy/rrc/manager.py
on_event(callback)
¶
part(room, hub_hash=None)
¶
Part a room on the first connected hub, or a specific hub.
Source code in lxmfy/rrc/manager.py
restore_sessions()
¶
Restore persisted hub sessions. Returns number of hubs reconnected.
Source code in lxmfy/rrc/manager.py
save_sessions()
¶
Persist hub hashes, rooms, and nick for crash recovery.
Source code in lxmfy/rrc/manager.py
send_action(room, text, hub_hash=None)
¶
Send an ACTION on the first connected hub, or a specific hub.
Source code in lxmfy/rrc/manager.py
send_message(room, text, hub_hash=None)
¶
Send a MSG on the first connected hub, or a specific hub.
Source code in lxmfy/rrc/manager.py
send_notice(room, text, hub_hash=None)
¶
Send a NOTICE on the first connected hub, or a specific hub.
Source code in lxmfy/rrc/manager.py
shutdown()
¶
Persist session state and tear down links without forgetting hubs.