* 使用messages.search直接搜索自己的消息 - 高效版本 * 从dme.ts移植的优化搜索函数
( client: TelegramClient, chatEntity: any, myId: bigInt.BigInteger, batchSize: number = 100 )
| 106 | chatEntity: any, |
| 107 | myId: bigInt.BigInteger, |
| 108 | batchSize: number = 100 |
| 109 | ): Promise<Api.Message[]> { |
| 110 | const allMyMessages: Api.Message[] = []; |
| 111 | let offsetId = 0; |
| 112 | |
| 113 | console.log(`[DA] 使用优化搜索模式,直接定位自己的消息`); |
| 114 | |
| 115 | try { |
| 116 | while (true) { |
| 117 | // 使用messages.search直接搜索自己的消息 |
| 118 | const searchResult = await client.invoke( |
| 119 | new Api.messages.Search({ |
| 120 | peer: chatEntity, |
| 121 | q: "", // 空查询搜索所有消息 |
| 122 | fromId: await client.getInputEntity(myId.toString()), // 关键:指定from_id为自己 |
| 123 | filter: new Api.InputMessagesFilterEmpty(), // 不过滤消息类型 |
| 124 | minDate: 0, |
| 125 | maxDate: 0, |
| 126 | offsetId: offsetId, |
| 127 | addOffset: 0, |
| 128 | limit: batchSize, |
| 129 | maxId: 0, |
| 130 | minId: 0, |
| 131 | hash: 0 as any |
| 132 | }) |
| 133 | ); |
| 134 | |
| 135 | // 正确处理搜索结果类型 |
| 136 | const resultMessages = (searchResult as any).messages; |
| 137 | if (!resultMessages || resultMessages.length === 0) { |
| 138 | console.log(`[DA] 搜索完成,共找到 ${allMyMessages.length} 条自己的消息`); |
| 139 | break; |
| 140 | } |
| 141 | |
| 142 | const messages = resultMessages.filter((m: any) => |
| 143 | m.className === "Message" && m.senderId?.toString() === myId.toString() |
| 144 | ); |
| 145 | |
| 146 | if (messages.length > 0) { |
| 147 | allMyMessages.push(...messages); |
| 148 | offsetId = messages[messages.length - 1].id; |
| 149 | console.log(`[DA] 批次搜索到 ${messages.length} 条消息,总计 ${allMyMessages.length} 条`); |
| 150 | } else { |
| 151 | break; |
| 152 | } |
| 153 | |
| 154 | // 避免API限制 |
| 155 | await sleep(200); |
| 156 | } |
| 157 | } catch (error: any) { |
| 158 | console.error("[DA] 优化搜索失败:", error); |
| 159 | return []; |
| 160 | } |
| 161 | |
| 162 | return allMyMessages; |
| 163 | } |
| 164 | |
| 165 | // 发送或更新进度到收藏夹 |