| 18 | } |
| 19 | |
| 20 | export class FeishuEventHandler { |
| 21 | private client: FeishuClient; |
| 22 | private nativeClient: Lark.Client; |
| 23 | private eventDispatcher: Lark.EventDispatcher; |
| 24 | private wsClient: Lark.WSClient | null = null; |
| 25 | private config: FeishuConfig; |
| 26 | private options: FeishuEventHandlerOptions; |
| 27 | private botOpenId: string | null = null; |
| 28 | private processedMessageIds: Set<string> = new Set(); // 消息去重 |
| 29 | private readonly maxProcessedMessages = 5000; // 最多缓存 5000 条消息 ID |
| 30 | private serviceStartTime: number = Date.now(); // 服务启动时间,用于忽略历史消息 |
| 31 | private processedIdsPath: string = './data/processed_ids.json'; |
| 32 | private saveInterval: NodeJS.Timeout | null = null; |
| 33 | |
| 34 | constructor(config: FeishuConfig, options: FeishuEventHandlerOptions = {}) { |
| 35 | this.config = config; |
| 36 | this.client = new FeishuClient(config); |
| 37 | this.nativeClient = this.client.getNativeClient(); |
| 38 | this.options = options; |
| 39 | this.eventDispatcher = new Lark.EventDispatcher({ |
| 40 | encryptKey: config.encryptKey, |
| 41 | verificationToken: config.verificationToken, |
| 42 | }); |
| 43 | |
| 44 | // 加载已处理的消息 ID |
| 45 | this.loadProcessedIds(); |
| 46 | |
| 47 | this.setupEventHandlers(); |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * 从文件加载已处理的消息 ID |
| 52 | */ |
| 53 | private loadProcessedIds(): void { |
| 54 | try { |
| 55 | if (fs.existsSync(this.processedIdsPath)) { |
| 56 | const data = fs.readFileSync(this.processedIdsPath, 'utf-8'); |
| 57 | const ids = JSON.parse(data) as string[]; |
| 58 | for (const id of ids) { |
| 59 | this.processedMessageIds.add(id); |
| 60 | } |
| 61 | logger.info(`Loaded ${this.processedMessageIds.size} processed message IDs from cache`); |
| 62 | } |
| 63 | } catch (error) { |
| 64 | logger.warn('Failed to load processed message IDs', { error }); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * 保存已处理的消息 ID 到文件 |
| 70 | */ |
| 71 | private saveProcessedIds(): void { |
| 72 | try { |
| 73 | const dir = path.dirname(this.processedIdsPath); |
| 74 | if (!fs.existsSync(dir)) { |
| 75 | fs.mkdirSync(dir, { recursive: true }); |
| 76 | } |
| 77 | const ids = Array.from(this.processedMessageIds); |
nothing calls this directly
no outgoing calls
no test coverage detected