如何在Dart Matrix机器人中配置私信加密及清理Hive数据库
使用famedly matrix-dart-sdk实现Matrix私信加密及数据库定时清理
一、正确激活Olm加密并发送加密消息
matrix-dart-sdk的加密模块依赖持久化数据库存储密钥、会话等核心数据,仅加载Olm库无法自动激活加密,必须通过配置databaseBuilder关联数据库才能启用。以下是完整的初始化及加密消息发送示例:
import 'dart:ffi'; import 'dart:io'; import 'package:olm/olm.dart' as olm; import 'package:matrix/matrix.dart'; void main() async { // 加载libcrypto(根据平台调整路径:Linux用libcrypto.so.3,macOS用libcrypto.dylib,Windows用libcrypto.dll) final libcrypto = DynamicLibrary.open('libcrypto.so.3'); await olm.init(libcrypto); print('Olm版本: ${olm.get_library_version()}'); const dbDirPath = './bot_encrypted_db'; // 初始化Client并绑定数据库,触发加密模块激活 final client = Client('IpxBot', databaseBuilder: (client) async { final dir = Directory(dbDirPath); await dir.create(recursive: true); final db = HiveCollectionsDatabase("bot_chat", dir.path); await db.open(); return db; }); // 登录Bot账号 await client.login( LoginType.password, identifier: UserID('@ipx_bot:your_homeserver.com'), password: 'your_bot_password', ); // 确认加密模块已启用 print('加密模块状态: ${client.encryption != null ? "已启用" : "未启用"}'); // 监听私信房间并回复加密消息 client.onRoomMessage.stream.listen((event) async { final room = event.room; // 判断是否为私信房间(直接聊天或仅两人的房间) if (room.isDirectChat || room.joinedMembers.length == 2) { final replyContent = EventContent( msgtype: MessageTypes.Text, body: '已收到你的消息:${event.content.body}', ); // 房间已加密则发送加密消息,否则发送明文 await room.sendEvent(replyContent, encrypt: room.encrypted); } }); }
二、Hive数据库定时清理方案
针对磁盘泄漏问题,可通过定时全量清理数据库目录+重启Client的方式解决,具体实现如下:
// 在main函数中添加定时清理任务 Timer.periodic(const Duration(hours: 1), (timer) async { await cleanDatabaseAndRestartClient(client, dbDirPath); }); // 数据库清理及Client重启逻辑 Future<void> cleanDatabaseAndRestartClient(Client client, String dbDirPath) async { try { // 停止Client并关闭数据库连接 await client.stop(); final db = client.database as HiveCollectionsDatabase; await db.close(); // 删除数据库目录下所有文件 final dbDir = Directory(dbDirPath); if (await dbDir.exists()) { await dbDir.delete(recursive: true); } // 重新创建数据库并初始化Client await dbDir.create(recursive: true); final newDb = HiveCollectionsDatabase("bot_chat", dbDirPath); await newDb.open(); client.dispose(); final newClient = Client('IpxBot', databaseBuilder: (_) async => newDb); await newClient.login( LoginType.password, identifier: UserID('@ipx_bot:your_homeserver.com'), password: 'your_bot_password', ); // 替换旧Client实例,确保后续消息监听正常 client = newClient; print('数据库清理完成,Client已重启'); } catch (e) { print('数据库清理失败: $e'); } }
注意事项
- 全量清理后,Bot会丢失所有历史加密会话,下次与用户通信时需重新建立会话,属于正常现象。
- 可根据需求调整清理粒度:若无需全量删除,可通过Hive API删除特定集合(如
olm_sessions、olm_account),但需查阅matrix-dart-sdk源码确认内部集合名称。 - 生产环境中建议在清理逻辑中加入异常捕获,避免Bot因清理失败崩溃。
内容的提问来源于stack exchange,提问作者Noh Kumado
相关产品推荐
相关产品推荐

