File size: 8,628 Bytes
76777b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
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
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
import { logForDebugging } from '../../utils/debug.js'
import { getTelegramRuntimeConfig } from './telegramConfig.js'
import type {
  TelegramGetMeResponse,
  TelegramGetUpdatesResponse,
  TelegramInboundEvent,
  TelegramRuntimeConfig,
  TelegramSendMessageResponse,
  TelegramServiceState,
  TelegramUpdate,
} from './telegramTypes.js'

type Listener = () => void
type InboundListener = (event: TelegramInboundEvent) => void

const TELEGRAM_API_BASE = 'https://api.telegram.org'
const MAX_TELEGRAM_MESSAGE_LENGTH = 4000
const POLL_TIMEOUT_SECONDS = 25
const RETRY_DELAY_MS = 3000

function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms))
}

function normalizeTelegramError(error: unknown): string {
  if (error instanceof Error) return error.message
  return String(error)
}

function chunkTelegramMessage(text: string): string[] {
  const normalized = text.trim()
  if (!normalized) return ['模型本轮没有返回可发送的文本结果。']

  const chunks: string[] = []
  for (let i = 0; i < normalized.length; i += MAX_TELEGRAM_MESSAGE_LENGTH) {
    chunks.push(normalized.slice(i, i + MAX_TELEGRAM_MESSAGE_LENGTH))
  }
  return chunks
}

function hasSameConfig(
  left: TelegramRuntimeConfig | undefined,
  right: TelegramRuntimeConfig,
): boolean {
  if (!left) return false
  return (
    left.botToken === right.botToken &&
    left.allowedUserIds.join(',') === right.allowedUserIds.join(',')
  )
}

class TelegramService {
  private listeners = new Set<Listener>()
  private inboundListeners = new Set<InboundListener>()
  private state: TelegramServiceState = { status: 'stopped' }
  private config?: TelegramRuntimeConfig
  private abortController: AbortController | null = null
  private runId = 0
  private nextUpdateOffset: number | undefined

  subscribe = (listener: Listener): (() => void) => {
    this.listeners.add(listener)
    return () => {
      this.listeners.delete(listener)
    }
  }

  subscribeToInbound = (listener: InboundListener): (() => void) => {
    this.inboundListeners.add(listener)
    return () => {
      this.inboundListeners.delete(listener)
    }
  }

  getStateSnapshot = (): TelegramServiceState => this.state

  async start(config: TelegramRuntimeConfig): Promise<void> {
    if (this.state.status === 'running' && hasSameConfig(this.config, config)) {
      return
    }

    await this.stop()

    const runId = ++this.runId
    const abortController = new AbortController()
    this.abortController = abortController
    this.config = config
    this.nextUpdateOffset = undefined

    this.setState({
      status: 'starting',
      lastError: undefined,
      botUsername: undefined,
      botDisplayName: undefined,
      startedAt: undefined,
      activeChatId: undefined,
      activeUserId: undefined,
    })

    try {
      const response = await this.callTelegram<TelegramGetMeResponse>(
        config,
        'getMe',
        {},
        abortController.signal,
      )

      if (runId !== this.runId || abortController.signal.aborted) return

      this.setState({
        status: 'running',
        botUsername: response.result?.username,
        botDisplayName: response.result?.first_name,
        startedAt: new Date().toISOString(),
        lastError: undefined,
      })

      logForDebugging(
        `[telegram] connected as @${response.result?.username ?? 'unknown'}`,
      )

      void this.pollLoop(runId, config, abortController.signal)
    } catch (error) {
      if (abortController.signal.aborted || runId !== this.runId) return
      const message = normalizeTelegramError(error)
      this.setState({
        status: 'stopped',
        lastError: message,
      })
      throw error
    }
  }

  async startFromSavedConfig(): Promise<void> {
    await this.start(getTelegramRuntimeConfig())
  }

  async restartFromSavedConfig(): Promise<void> {
    await this.startFromSavedConfig()
  }

  async stop(): Promise<void> {
    this.runId++
    this.abortController?.abort()
    this.abortController = null
    this.config = undefined
    this.nextUpdateOffset = undefined

    if (this.state.status !== 'stopped') {
      this.setState({
        ...this.state,
        status: 'stopped',
        startedAt: undefined,
      })
    }
  }

  async sendMessage(chatId: string, text: string): Promise<void> {
    if (!this.config) {
      throw new Error('Telegram service is not running')
    }

    for (const chunk of chunkTelegramMessage(text)) {
      await this.callTelegram<TelegramSendMessageResponse>(
        this.config,
        'sendMessage',
        {
          chat_id: Number(chatId),
          text: chunk,
        },
      )
    }
  }

  private setState(nextState: TelegramServiceState): void {
    this.state = nextState
    for (const listener of this.listeners) {
      listener()
    }
  }

  private patchState(patch: Partial<TelegramServiceState>): void {
    this.setState({
      ...this.state,
      ...patch,
    })
  }

  private emitInbound(event: TelegramInboundEvent): void {
    for (const listener of this.inboundListeners) {
      listener(event)
    }
  }

  private async pollLoop(
    runId: number,
    config: TelegramRuntimeConfig,
    signal: AbortSignal,
  ): Promise<void> {
    while (!signal.aborted && runId === this.runId) {
      try {
        const response = await this.callTelegram<TelegramGetUpdatesResponse>(
          config,
          'getUpdates',
          {
            offset: this.nextUpdateOffset,
            timeout: POLL_TIMEOUT_SECONDS,
            allowed_updates: ['message'],
          },
          signal,
        )

        if (signal.aborted || runId !== this.runId) return

        if (this.state.lastError) {
          this.patchState({ lastError: undefined })
        }

        for (const update of response.result ?? []) {
          this.handleUpdate(update, config)
        }
      } catch (error) {
        if (signal.aborted || runId !== this.runId) return

        const message = normalizeTelegramError(error)
        logForDebugging(`[telegram] polling failed: ${message}`, {
          level: 'error',
        })
        this.patchState({ lastError: message })
        await sleep(RETRY_DELAY_MS)
      }
    }
  }

  private handleUpdate(
    update: TelegramUpdate,
    config: TelegramRuntimeConfig,
  ): void {
    this.nextUpdateOffset = update.update_id + 1

    const message = update.message
    const chatId = message?.chat?.id
    const userId = message?.from?.id

    if (!message || chatId === undefined || userId === undefined) return
    if (message.from?.is_bot) return
    if (message.chat?.type !== 'private') return

    const normalizedChatId = String(chatId)
    const normalizedUserId = String(userId)

    if (!config.allowedUserIds.includes(normalizedUserId)) {
      void this.sendMessage(
        normalizedChatId,
        '这个 Telegram user id 尚未被当前 /telegram 配置授权。',
      ).catch(() => {})
      return
    }

    this.patchState({
      activeChatId: normalizedChatId,
      activeUserId: normalizedUserId,
    })

    const text = message.text?.trim()

    if (!text) {
      void this.sendMessage(
        normalizedChatId,
        '当前只支持文本消息,请发送纯文本内容。',
      ).catch(() => {})
      return
    }

    if (text === '/start') {
      void this.sendMessage(
        normalizedChatId,
        'Telegram 已连接到当前 VersperClaw 会话。直接发送文本即可开始远程对话。',
      ).catch(() => {})
      return
    }

    this.emitInbound({
      kind: 'inbound-message',
      chatId: normalizedChatId,
      userId: normalizedUserId,
      text,
      messageId: message.message_id,
      updateId: update.update_id,
    })
  }

  private async callTelegram<T>(
    config: TelegramRuntimeConfig,
    method: string,
    payload: Record<string, unknown>,
    signal?: AbortSignal,
  ): Promise<T> {
    const response = await fetch(
      `${TELEGRAM_API_BASE}/bot${config.botToken}/${method}`,
      {
        method: 'POST',
        headers: {
          'content-type': 'application/json',
        },
        body: JSON.stringify(payload),
        signal,
      },
    )

    if (!response.ok) {
      throw new Error(`Telegram API ${method} failed with HTTP ${response.status}`)
    }

    const json = await response.json() as {
      ok?: boolean
      description?: string
    }

    if (!json.ok) {
      throw new Error(
        `Telegram API ${method} failed: ${json.description ?? 'unknown error'}`,
      )
    }

    return json as T
  }
}

export const telegramService = new TelegramService()