Преглед изворни кода

优化 TgClientService 的连接配置,增加重试机制和 WebSocket 支持,同时增强错误处理和日志记录,以提高连接稳定性和可调试性。

wuyi пре 1 месец
родитељ
комит
2ff394cec7
1 измењених фајлова са 20 додато и 10 уклоњено
  1. 20 10
      src/services/tgClient.service.ts

+ 20 - 10
src/services/tgClient.service.ts

@@ -59,12 +59,27 @@ export class TgClientService {
     }
 
     const stringSession = new StringSession(sessionString)
-    this.client = new TelegramClient(stringSession, this.apiId, this.apiHash, {
-      connectionRetries: 5
-    })
+    const connectionOptions = {
+      connectionRetries: 5,
+      retryDelay: 2000,
+      requestRetries: 5,
+      useWSS: true
+    }
+
+    this.client = new TelegramClient(stringSession, this.apiId, this.apiHash, connectionOptions)
 
-    this.app.log.info('正在建立连接...')
-    await this.client.connect()
+    this.app.log.info(
+      `正在建立连接... useWSS=${connectionOptions.useWSS ? 'true' : 'false'} (443 优先), retries=${
+        connectionOptions.connectionRetries
+      }`
+    )
+    try {
+      await this.client.connect()
+    } catch (err) {
+      const errorMessage = err instanceof Error ? err.message : String(err)
+      this.app.log.error({ msg: '连接 Telegram 失败', error: errorMessage, useWSS: connectionOptions.useWSS })
+      throw err
+    }
 
     if (!this.client.connected) {
       throw new Error('TelegramClient 连接失败,请检查网络或 Session 是否有效')
@@ -117,7 +132,6 @@ export class TgClientService {
 
       if (typeof parsedTarget === 'string' && parsedTarget.startsWith('+')) {
         this.app.log.info('手机号导入联系人...')
-        // 手机号
         const result = await client.invoke(
           new Api.contacts.ImportContacts({
             contacts: [
@@ -136,7 +150,6 @@ export class TgClientService {
 
         targetPeer = user
       } else {
-        // 用户名 用户 id
         targetPeer = await client.getEntity(parsedTarget)
       }
 
@@ -225,19 +238,16 @@ export class TgClientService {
       className: entityInfo.className || '未知'
     }
 
-    // 记录 ID
     if (entityInfo.id !== undefined) {
       logData.id = entityInfo.id.toString()
     }
 
-    // 记录名称信息
     if (entityInfo.title) {
       logData.title = entityInfo.title
     } else if (entityInfo.firstName) {
       logData.name = `${entityInfo.firstName} ${entityInfo.lastName || ''}`.trim()
     }
 
-    // 记录用户名
     if (entityInfo.username) {
       logData.username = entityInfo.username
     }