核心组件¶
LXMFBot¶
主机器人类,负责消息路由、命令处理和机器人生命周期管理。
from lxmfy import LXMFBot
bot = LXMFBot(
name="MyBot",
announce=600,
announce_immediately=True,
admins=set(),
hot_reloading=False,
rate_limit=5,
cooldown=60,
max_warnings=3,
warning_timeout=300,
command_prefix="/",
cogs_dir="cogs",
cogs_enabled=True,
permissions_enabled=False,
storage_type="json", # "json"、"sqlite" 或 "memory"
storage_path="data",
first_message_enabled=True,
event_logging_enabled=True,
max_logged_events=1000,
event_middleware_enabled=True,
announce_enabled=True,
signature_verification_enabled=False,
require_message_signatures=False,
identity_pinning_enabled=False,
message_persistence_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,
landlock_enabled=True,
nlp_enabled=False,
nlp_threshold=0.5,
link_support_enabled=False,
lxmf_commands_enabled=True,
message_queue_size=50,
reticulum_config_dir=None, # 或 LXMFY_RETICULUM_CONFIG_DIR / "~/.reticulum"
rrc_enabled=False,
rrc_hubs=[],
rrc_rooms=[],
rrc_nick=None,
rrc_dest_name="rrc.hub",
rrc_auto_reconnect=True,
rrc_persist_sessions=True,
)
主要方法¶
get_landlock_status():返回机器人进程的 Landlock LSM 沙箱 可用性和激活状态run(delay=10):启动机器人主循环send(destination, message, title="Reply", lxmf_fields=None, stamp_cost=None, opportunistic=None): 向目标发送消息,可选携带自定义 LXMF 字段、邮票成本覆盖和 机会式发送(先尝试直接投递,若已配置则立即回退到传播 节点)。send_with_attachment(destination, message, attachment, title="Reply", stamp_cost=None, opportunistic=None): 发送带附件的消息command(name, description="No description provided", admin_only=False, threaded=False): 注册命令的装饰器。设threaded=True可在独立线程中运行 命令回调。命令支持带类型注解的参数,可自动转换。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 link。允许自定义app_name和aspects(默认为 "lxmf" 和 "delivery")。on_link(callback):注册传入 RNS link 的处理器。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():处理所有消息的装饰器(在命令处理之前 调用)on_reaction():处理传入回应的装饰器。处理器接收(sender, reaction),其中 reaction 带有reaction_to、reaction_emoji和reaction_sender键react(destination, message_hash, reaction):通过 LXMFFIELD_REACTION字段对一条消息发送回应validate():对机器人配置运行校验检查connect_rrc(hub_hash, rooms=None, nick=None, dest_name=None, auto_reconnect=None): 作为客户端连接到 RRC hubdisconnect_rrc(hub_hash=None):断开一个或全部 RRC hub 会话on_rrc(callback=None):注册 RRC 事件处理器的装饰器或方法 (handler(event, client, payload))rrc:用于多 hub 会话的RRCManager实例
通过 LXMF 字段实现结构化命令¶
机器人可以接收通过 LXMF FIELD_COMMANDS(0x09)发送的命令,
并自动以 FIELD_RESULTS(0x0A)回复。这让结构化请求/响应
工作流可以与普通文本命令并存。
传入的 FIELD_COMMANDS 会被解析并路由到与文本命令相同的命令
注册表,共享权限检查、类型注解参数解析、线程化和中间件。
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 字段字典
# 如果命令带有 request_id,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。
要禁用字段命令处理,在 BotConfig 中设置
lxmf_commands_enabled=False。
回应¶
回应以 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"] - 目标消息的十六进制哈希
# 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 中访问以保持兼容。
存储¶
框架提供三种存储后端:
JSONStorage¶
SQLiteStorage¶
MemoryStorage¶
命令¶
命令注册和处理:
@bot.command(name="hello", description="Says hello")
def hello(ctx):
ctx.reply(f"Hello {ctx.sender}!")
类型注解参数¶
命令会根据回调函数中的类型注解自动解析和转换参数。
@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}")
帮助系统¶
框架内置交互式帮助生成器,基于 Cog 和 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()。
事件¶
用于处理各种机器人事件的事件系统:
测试¶
项目测试包含仓库测试套件中的可靠性和压力场景。使用仓库的 测试运行器执行它们。
高级可靠性测试套件¶
框架包含一套针对严苛环境的大规模自动化测试:
- Manifold Testing:校验 NLP 意图向量空间的数学拓扑。
- Chaos Engineering:模拟位衰减、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")
中间件¶
用于处理消息和事件的中间件系统:
@bot.middleware.register(MiddlewareType.PRE_COMMAND)
def pre_command_middleware(ctx):
# 在命令执行前处理
pass
附件¶
支持发送文件、图片和音频:
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)
调度器¶
任务调度系统:
签名¶
LXMFy 为 LXMF 内置的加密消息签名与校验提供配置选项:
from lxmfy import LXMFBot
bot = LXMFBot(
name="SecureBot",
signature_verification_enabled=True, # 启用签名检查
require_message_signatures=False # 设为 True 可拒绝未签名消息
)
签名处理
LXMF 使用 RNS 身份自动处理所有加密签名和校验。LXMFy 的
SignatureManager 是一个配置层,负责:
- 控制是否强制执行签名校验
- 确定对未签名消息的策略(接受或拒绝)
- 与权限系统集成(例如可信用户可跳过校验)
实际的加密操作由 LXMF/RNS 执行,而不是 LXMFy。
Landlock LSM 沙箱¶
在支持 Landlock 的 Linux 内核(5.13+)上,LXMFy 可以限制 机器人进程和外部脚本 Cog 的文件系统访问。
机器人进程沙箱
当 landlock_enabled=True(默认)且未运行于 test_mode 时,
机器人会在初始化期间调用 apply_landlock_sandbox()。系统目录
为只读;机器人存储、配置、Cog、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:即使内核支持也禁用 LandlockLXMFY_LANDLOCK=1:在 Linux 上无论自动检测结果如何都尝试 Landlock- 未设置:遵循
landlock_enabled和内核自动检测
外部 Cog 沙箱
脚本 Cog 使用 external_cogs_sandbox_type。在 auto 模式下
优先使用 Landlock(若可用),因为它不需要外部工具。完整的
沙箱选项列表见创建机器人指南。
身份固定¶
LXMFy 支持可选的身份固定,防止身份被轮换或泄露后遭到冒充。 启用后,机器人会把一个 LXMF 地址“固定”到首次见到的公钥。
SignatureManager 方法¶
当 signature_verification_enabled=True 时,可通过
bot.signature_manager 访问 SignatureManager:
should_verify_message(sender):判断来自给定发送者的消息 是否应校验handle_unsigned_message(sender, message_hash):按策略处理 缺少有效签名的消息
LXMF 签名的工作原理¶
LXMF 在 pack() 操作期间使用发送者的 RNS 身份自动为所有出站
消息签名。接收消息时,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"
)
# 传播节点哈希应该是 Reticulum 网络上
# 一个有效的 LXMF 传播节点
自动重试¶
为失败的直接投递配置自动重试次数:
bot = LXMFBot(
name="ReliableBot",
direct_delivery_retries=5, # 直接投递最多重试 5 次
propagation_fallback_enabled=True
)
bot.send(destination_hash, "Important message")
# direct_delivery_retries 默认为 3
# 重试逻辑会自动处理投递回调
重试系统会跟踪每个目标的投递尝试次数,并自动重试失败的投递。 投递成功后会重置该目标的重试计数器。
消息持久化¶
出站消息可以持久化到磁盘,确保机器人重启后仍能送达。持久化
默认开启。内存出站队列有上限(message_queue_size,默认 50),
满了之后会丢弃最旧的消息。无效的目标哈希不会被恢复。
消息处理器¶
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. 命令处理(如果消息以命令前缀开头)
Reticulum Relay Chat (RRC)¶
机器人可以通过 RNS Link 以 CBOR 封包加入
RRC hub。包:lxmfy.rrc。
BotConfig 选项¶
rrc_enabled(bool,默认False):启动时连接已配置的 hubrrc_hubs(十六进制哈希列表):hub 目标哈希rrc_rooms(str 列表):WELCOME 之后自动加入的房间rrc_nick(str 或 None):HELLO 和房间消息中的昵称rrc_dest_name(str,默认"rrc.hub"):用于构造 hub 目标的目标名称rrc_auto_reconnect(bool,默认True):link 断开后自动 重连rrc_persist_sessions(bool,默认True):跨重启持久化 hub 和房间reticulum_config_dir(str 或 None):Reticulum 配置目录。 也可用LXMFY_RETICULUM_CONFIG_DIR设置。使用与 MeshChatX 相同的配置(通常是~/.reticulum),这样 hub 的 announce 才可见。
示例¶
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:单 hub 会话RRCManager:多 hub 管理器(bot.rrc)RRCMessage:房间事件负载(kind、room、text、nick、src、mention等)RRC_VERSION:线路协议版本常量
传给 @bot.on_rrc 处理器的常见事件包括 status、welcome、
joined、parted、msg、notice、action、motd、
error 和 rtt。
模板¶
框架包含若干可直接使用的机器人模板:
EchoBot¶
简单的 echo 机器人,复述收到的消息:
NoteBot¶
使用 JSON 存储的笔记机器人:
ReminderBot¶
使用 SQLite 存储的提醒机器人:
RRCBot¶
RRC 房间机器人,加入配置的 hub 并回复 @提及。默认 hub 为
664fc0e8d2e448658e37bb3f34e6c88f,房间为 #general,并在
可用时使用 ~/.reticulum。
from lxmfy.templates import RRCBot
bot = RRCBot(
hubs=["664fc0e8d2e448658e37bb3f34e6c88f"],
rooms=["general"],
nick="RRCBot",
reticulum_config_dir="~/.reticulum",
)
bot.run()
CLI 工具¶
框架提供用于机器人管理的命令行工具:
# 创建一个新机器人
lxmfy create mybot
# 从模板创建机器人
lxmfy create --template echo mybot
lxmfy create --template rrc my_rrc_bot
# 运行模板机器人
lxmfy run echo
lxmfy run rrc
# 用一条消息测试签名校验
lxmfy signatures test
# 启用签名校验
lxmfy signatures enable
# 禁用签名校验
lxmfy signatures disable
错误处理¶
在 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 | |
__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 | |
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" or "sqlite"). 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
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
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
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
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 | |
__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
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 | |
__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
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 | |
__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 |