@michengai/dsh-im-connect 0.1.20 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +2 -2
- package/README.md +2 -2
- package/SECURITY.md +1 -1
- package/lib/channels/dingtalk-card.d.ts.map +1 -1
- package/lib/channels/dingtalk-card.js +3 -0
- package/lib/channels/dingtalk-card.js.map +1 -1
- package/lib/channels/dingtalk.d.ts.map +1 -1
- package/lib/channels/dingtalk.js +6 -1
- package/lib/channels/dingtalk.js.map +1 -1
- package/lib/channels/feishu.d.ts +9 -0
- package/lib/channels/feishu.d.ts.map +1 -1
- package/lib/channels/feishu.js +23 -6
- package/lib/channels/feishu.js.map +1 -1
- package/lib/channels/qq.d.ts.map +1 -1
- package/lib/channels/qq.js +17 -1
- package/lib/channels/qq.js.map +1 -1
- package/lib/channels/telegram.d.ts.map +1 -1
- package/lib/channels/telegram.js +17 -4
- package/lib/channels/telegram.js.map +1 -1
- package/lib/channels/wecom.d.ts +7 -1
- package/lib/channels/wecom.d.ts.map +1 -1
- package/lib/channels/wecom.js +44 -11
- package/lib/channels/wecom.js.map +1 -1
- package/lib/channels/weixin.d.ts +3 -0
- package/lib/channels/weixin.d.ts.map +1 -1
- package/lib/channels/weixin.js +68 -15
- package/lib/channels/weixin.js.map +1 -1
- package/lib/engine/abort.d.ts +4 -0
- package/lib/engine/abort.d.ts.map +1 -0
- package/lib/engine/abort.js +26 -0
- package/lib/engine/abort.js.map +1 -0
- package/lib/engine/atomic-file.d.ts +5 -0
- package/lib/engine/atomic-file.d.ts.map +1 -0
- package/lib/engine/atomic-file.js +46 -0
- package/lib/engine/atomic-file.js.map +1 -0
- package/lib/engine/json-state.d.ts.map +1 -1
- package/lib/engine/json-state.js +7 -5
- package/lib/engine/json-state.js.map +1 -1
- package/lib/engine/secure-file.d.ts.map +1 -1
- package/lib/engine/secure-file.js +2 -12
- package/lib/engine/secure-file.js.map +1 -1
- package/lib/engine/seen-store.d.ts.map +1 -1
- package/lib/engine/seen-store.js +4 -4
- package/lib/engine/seen-store.js.map +1 -1
- package/lib/engine/session-store.d.ts.map +1 -1
- package/lib/engine/session-store.js +7 -5
- package/lib/engine/session-store.js.map +1 -1
- package/lib/manager.d.ts.map +1 -1
- package/lib/manager.js +4 -9
- package/lib/manager.js.map +1 -1
- package/package.json +1 -1
- package/src/channels/dingtalk-card.ts +195 -192
- package/src/channels/dingtalk.ts +144 -140
- package/src/channels/feishu.ts +92 -66
- package/src/channels/qq.ts +303 -288
- package/src/channels/telegram.ts +170 -158
- package/src/channels/wecom.ts +209 -177
- package/src/channels/weixin.ts +158 -112
- package/src/engine/abort.ts +25 -0
- package/src/engine/access.ts +34 -34
- package/src/engine/atomic-file.ts +36 -0
- package/src/engine/json-state.ts +16 -15
- package/src/engine/secure-file.ts +7 -13
- package/src/engine/seen-store.ts +39 -39
- package/src/engine/session-store.ts +40 -39
- package/src/manager.ts +346 -350
package/src/channels/telegram.ts
CHANGED
|
@@ -1,175 +1,187 @@
|
|
|
1
1
|
import type { ChannelAdapter, ImMessage, ReplyStream } from '../engine/types.js'
|
|
2
2
|
import { JsonStateFile } from '../engine/json-state.js'
|
|
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
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
let
|
|
32
|
-
let
|
|
33
|
-
let
|
|
3
|
+
import { sleepWithSignal, timeoutSignal } from '../engine/abort.js'
|
|
4
|
+
|
|
5
|
+
export interface TelegramConfig {
|
|
6
|
+
token?: string
|
|
7
|
+
stateDir?: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface TgUpdate {
|
|
11
|
+
update_id: number
|
|
12
|
+
message?: {
|
|
13
|
+
message_id: number
|
|
14
|
+
chat: { id: number; type: string }
|
|
15
|
+
from?: { id: number; username?: string; first_name?: string; is_bot?: boolean }
|
|
16
|
+
text?: string
|
|
17
|
+
caption?: string
|
|
18
|
+
entities?: Array<{ type: string; offset: number; length: number }>
|
|
19
|
+
reply_to_message?: { from?: { id: number } }
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const API = 'https://api.telegram.org'
|
|
24
|
+
|
|
25
|
+
export function createTelegramChannel(config: TelegramConfig, log: (line: string) => void): ChannelAdapter | undefined {
|
|
26
|
+
const token = config.token?.trim()
|
|
27
|
+
if (!token) return undefined
|
|
28
|
+
const cursorFile = new JsonStateFile(config.stateDir ? `${config.stateDir.replace(/[\\/]$/, '')}/cursor.json` : '', { offset: 0 })
|
|
29
|
+
const persist = Boolean(config.stateDir)
|
|
30
|
+
|
|
31
|
+
let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
|
|
32
|
+
let offset = persist ? cursorFile.read().offset : 0
|
|
33
|
+
let stopped = false
|
|
34
|
+
let lastError = ''
|
|
34
35
|
let botId = ''
|
|
35
36
|
let username = ''
|
|
37
|
+
let lifecycle: AbortController | undefined
|
|
38
|
+
let pollTask: Promise<void> | undefined
|
|
36
39
|
|
|
37
|
-
async function api<T>(method: string, body: Record<string, unknown
|
|
40
|
+
async function api<T>(method: string, body: Record<string, unknown>, timeoutMs = 30_000): Promise<T> {
|
|
38
41
|
const res = await fetch(`${API}/bot${token}/${method}`, {
|
|
39
|
-
method: 'POST',
|
|
42
|
+
method: 'POST',
|
|
40
43
|
headers: { 'content-type': 'application/json' },
|
|
41
44
|
body: JSON.stringify(body),
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
45
|
+
signal: timeoutSignal(timeoutMs, lifecycle?.signal),
|
|
46
|
+
})
|
|
47
|
+
const data = (await res.json()) as { ok: boolean; description?: string; error_code?: number; result: T }
|
|
48
|
+
if (!data.ok) {
|
|
49
|
+
const error = new Error(`telegram ${method}: ${data.description ?? 'unknown'}`)
|
|
50
|
+
if (data.error_code === 401) (error as Error & { code?: string }).code = 'telegram-401'
|
|
51
|
+
throw error
|
|
52
|
+
}
|
|
53
|
+
return data.result
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function mentioned(message: NonNullable<TgUpdate['message']>): boolean {
|
|
57
|
+
if (!username || !message.text || !Array.isArray(message.entities)) return false
|
|
58
|
+
return message.entities.some((entity) => {
|
|
59
|
+
if (entity.type !== 'mention') return false
|
|
60
|
+
return message.text!.slice(entity.offset, entity.offset + entity.length).toLowerCase() === `@${username.toLowerCase()}`
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function pollLoop(): Promise<void> {
|
|
65
|
+
while (!stopped) {
|
|
66
|
+
try {
|
|
63
67
|
const updates = await api<TgUpdate[]>('getUpdates', {
|
|
64
|
-
offset,
|
|
65
|
-
timeout: 25,
|
|
66
|
-
allowed_updates: ['message'],
|
|
67
|
-
})
|
|
68
|
-
lastError = ''
|
|
69
|
-
for (const update of updates) {
|
|
70
|
-
// Telegram offset 是 at-most-once 取舍:先确认游标可避免崩溃重启后重复驱动 agent,代价是极端情况下丢一条未完成消息。
|
|
71
|
-
offset = update.update_id + 1
|
|
72
|
-
if (persist) cursorFile.write({ offset })
|
|
73
|
-
const message = update.message
|
|
74
|
-
if (!message || message.from?.is_bot) continue
|
|
75
|
-
if (!['private', 'group', 'supergroup'].includes(message.chat.type)) continue
|
|
76
|
-
const direct = message.chat.type === 'private'
|
|
77
|
-
const addressed = direct
|
|
78
|
-
|| String(message.reply_to_message?.from?.id ?? '') === botId
|
|
79
|
-
|| mentioned(message)
|
|
80
|
-
let text = message.text ?? message.caption ?? ''
|
|
81
|
-
if (username) text = text.replace(new RegExp(`@${username}\\b`, 'ig'), '').trim()
|
|
82
|
-
void handler?.({
|
|
83
|
-
chatId: String(message.chat.id),
|
|
84
|
-
userId: message.from ? String(message.from.id) : undefined,
|
|
85
|
-
username: message.from?.username ?? message.from?.first_name,
|
|
86
|
-
text,
|
|
87
|
-
kind: direct ? 'dm' : 'group',
|
|
88
|
-
addressed,
|
|
89
|
-
messageId: String(update.update_id),
|
|
90
|
-
})
|
|
91
|
-
}
|
|
92
|
-
} catch (error) {
|
|
93
|
-
lastError = error instanceof Error ? error.message : String(error)
|
|
94
|
-
log(`[telegram] 轮询错误: ${lastError}`)
|
|
95
|
-
if (stopped) break
|
|
96
|
-
await
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
return {
|
|
102
|
-
id: 'telegram',
|
|
103
|
-
label: 'Telegram',
|
|
104
|
-
maxMessageLength: 4000,
|
|
68
|
+
offset,
|
|
69
|
+
timeout: 25,
|
|
70
|
+
allowed_updates: ['message'],
|
|
71
|
+
}, 35_000)
|
|
72
|
+
lastError = ''
|
|
73
|
+
for (const update of updates) {
|
|
74
|
+
// Telegram offset 是 at-most-once 取舍:先确认游标可避免崩溃重启后重复驱动 agent,代价是极端情况下丢一条未完成消息。
|
|
75
|
+
offset = update.update_id + 1
|
|
76
|
+
if (persist) cursorFile.write({ offset })
|
|
77
|
+
const message = update.message
|
|
78
|
+
if (!message || message.from?.is_bot) continue
|
|
79
|
+
if (!['private', 'group', 'supergroup'].includes(message.chat.type)) continue
|
|
80
|
+
const direct = message.chat.type === 'private'
|
|
81
|
+
const addressed = direct
|
|
82
|
+
|| String(message.reply_to_message?.from?.id ?? '') === botId
|
|
83
|
+
|| mentioned(message)
|
|
84
|
+
let text = message.text ?? message.caption ?? ''
|
|
85
|
+
if (username) text = text.replace(new RegExp(`@${username}\\b`, 'ig'), '').trim()
|
|
86
|
+
void handler?.({
|
|
87
|
+
chatId: String(message.chat.id),
|
|
88
|
+
userId: message.from ? String(message.from.id) : undefined,
|
|
89
|
+
username: message.from?.username ?? message.from?.first_name,
|
|
90
|
+
text,
|
|
91
|
+
kind: direct ? 'dm' : 'group',
|
|
92
|
+
addressed,
|
|
93
|
+
messageId: String(update.update_id),
|
|
94
|
+
})
|
|
95
|
+
}
|
|
96
|
+
} catch (error) {
|
|
97
|
+
lastError = error instanceof Error ? error.message : String(error)
|
|
98
|
+
log(`[telegram] 轮询错误: ${lastError}`)
|
|
99
|
+
if (stopped) break
|
|
100
|
+
await sleepWithSignal(3000, lifecycle?.signal).catch(() => undefined)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
id: 'telegram',
|
|
107
|
+
label: 'Telegram',
|
|
108
|
+
maxMessageLength: 4000,
|
|
105
109
|
async start() {
|
|
110
|
+
lifecycle?.abort()
|
|
111
|
+
lifecycle = new AbortController()
|
|
106
112
|
stopped = false
|
|
107
|
-
const me = await api<{ id: number; username?: string; is_bot: boolean }>('getMe', {})
|
|
108
|
-
botId = String(me.id)
|
|
109
|
-
username = me.username ?? ''
|
|
110
|
-
const hook = await api<{ url?: string }>('getWebhookInfo', {})
|
|
113
|
+
const me = await api<{ id: number; username?: string; is_bot: boolean }>('getMe', {})
|
|
114
|
+
botId = String(me.id)
|
|
115
|
+
username = me.username ?? ''
|
|
116
|
+
const hook = await api<{ url?: string }>('getWebhookInfo', {})
|
|
111
117
|
if (hook.url) throw Object.assign(new Error('该 Telegram 机器人已配置 Webhook,请先在原服务中移除。'), { code: 'webhook-configured' })
|
|
112
118
|
log('[telegram] 开始长轮询')
|
|
113
|
-
|
|
119
|
+
pollTask = pollLoop().catch((error) => {
|
|
120
|
+
if (!stopped) log(`[telegram] 轮询循环退出: ${error instanceof Error ? error.message : String(error)}`)
|
|
121
|
+
})
|
|
114
122
|
},
|
|
115
123
|
async stop() {
|
|
116
124
|
stopped = true
|
|
125
|
+
lifecycle?.abort()
|
|
126
|
+
await pollTask?.catch(() => undefined)
|
|
127
|
+
pollTask = undefined
|
|
128
|
+
lifecycle = undefined
|
|
117
129
|
if (persist) cursorFile.write({ offset })
|
|
118
|
-
},
|
|
119
|
-
async send(chatId, text) {
|
|
120
|
-
await api('sendMessage', { chat_id: Number(chatId), text })
|
|
121
|
-
},
|
|
122
|
-
async sendAction(chatId) {
|
|
123
|
-
await api('sendChatAction', { chat_id: Number(chatId), action: 'typing' }).catch(() => undefined)
|
|
124
|
-
},
|
|
125
|
-
async beginReply(chatId): Promise<ReplyStream> {
|
|
126
|
-
const first = await api<{ message_id: number }>('sendMessage', { chat_id: Number(chatId), text: '…' })
|
|
127
|
-
let last = '…'
|
|
128
|
-
let timer: ReturnType<typeof setTimeout> | undefined
|
|
129
|
-
let pending: string | undefined
|
|
130
|
-
let inflight = Promise.resolve()
|
|
131
|
-
|
|
132
|
-
const flush = async (text: string, allowSend: boolean) => {
|
|
133
|
-
const next = text.slice(0, 4000) || '…'
|
|
134
|
-
if (next === last) return
|
|
135
|
-
// last 只在发送成功后更新:失败时保留旧值,finish 才能靠 sendMessage 兜底送出全文
|
|
136
|
-
try {
|
|
137
|
-
await api('editMessageText', { chat_id: Number(chatId), message_id: first.message_id, text: next })
|
|
138
|
-
last = next
|
|
139
|
-
} catch (error) {
|
|
140
|
-
const detail = error instanceof Error ? error.message : String(error)
|
|
141
|
-
if (detail.includes('message is not modified')) {
|
|
142
|
-
last = next
|
|
143
|
-
return
|
|
144
|
-
}
|
|
145
|
-
if (!allowSend) return
|
|
146
|
-
await api('sendMessage', { chat_id: Number(chatId), text: next })
|
|
147
|
-
last = next
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
return {
|
|
152
|
-
async update(text) {
|
|
153
|
-
pending = text
|
|
154
|
-
if (timer) return
|
|
155
|
-
timer = setTimeout(() => {
|
|
156
|
-
timer = undefined
|
|
157
|
-
const next = pending
|
|
158
|
-
pending = undefined
|
|
159
|
-
if (next !== undefined) inflight = inflight.then(() => flush(next, false))
|
|
160
|
-
}, 400)
|
|
161
|
-
},
|
|
162
|
-
async finish(text) {
|
|
163
|
-
if (timer) {
|
|
164
|
-
clearTimeout(timer)
|
|
165
|
-
timer = undefined
|
|
166
|
-
}
|
|
167
|
-
await inflight.catch(() => undefined)
|
|
168
|
-
await flush(text || pending || last, true)
|
|
169
|
-
},
|
|
170
|
-
}
|
|
171
|
-
},
|
|
172
|
-
setMessageHandler(h) { handler = h },
|
|
173
|
-
status() { return stopped ? '已停止' : lastError ? '轮询异常(详情见本机日志)' : '轮询中' },
|
|
174
|
-
}
|
|
175
|
-
}
|
|
130
|
+
},
|
|
131
|
+
async send(chatId, text) {
|
|
132
|
+
await api('sendMessage', { chat_id: Number(chatId), text })
|
|
133
|
+
},
|
|
134
|
+
async sendAction(chatId) {
|
|
135
|
+
await api('sendChatAction', { chat_id: Number(chatId), action: 'typing' }).catch(() => undefined)
|
|
136
|
+
},
|
|
137
|
+
async beginReply(chatId): Promise<ReplyStream> {
|
|
138
|
+
const first = await api<{ message_id: number }>('sendMessage', { chat_id: Number(chatId), text: '…' })
|
|
139
|
+
let last = '…'
|
|
140
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
141
|
+
let pending: string | undefined
|
|
142
|
+
let inflight = Promise.resolve()
|
|
143
|
+
|
|
144
|
+
const flush = async (text: string, allowSend: boolean) => {
|
|
145
|
+
const next = text.slice(0, 4000) || '…'
|
|
146
|
+
if (next === last) return
|
|
147
|
+
// last 只在发送成功后更新:失败时保留旧值,finish 才能靠 sendMessage 兜底送出全文
|
|
148
|
+
try {
|
|
149
|
+
await api('editMessageText', { chat_id: Number(chatId), message_id: first.message_id, text: next })
|
|
150
|
+
last = next
|
|
151
|
+
} catch (error) {
|
|
152
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
153
|
+
if (detail.includes('message is not modified')) {
|
|
154
|
+
last = next
|
|
155
|
+
return
|
|
156
|
+
}
|
|
157
|
+
if (!allowSend) return
|
|
158
|
+
await api('sendMessage', { chat_id: Number(chatId), text: next })
|
|
159
|
+
last = next
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
async update(text) {
|
|
165
|
+
pending = text
|
|
166
|
+
if (timer) return
|
|
167
|
+
timer = setTimeout(() => {
|
|
168
|
+
timer = undefined
|
|
169
|
+
const next = pending
|
|
170
|
+
pending = undefined
|
|
171
|
+
if (next !== undefined) inflight = inflight.then(() => flush(next, false))
|
|
172
|
+
}, 400)
|
|
173
|
+
},
|
|
174
|
+
async finish(text) {
|
|
175
|
+
if (timer) {
|
|
176
|
+
clearTimeout(timer)
|
|
177
|
+
timer = undefined
|
|
178
|
+
}
|
|
179
|
+
await inflight.catch(() => undefined)
|
|
180
|
+
await flush(text || pending || last, true)
|
|
181
|
+
},
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
setMessageHandler(h) { handler = h },
|
|
185
|
+
status() { return stopped ? '已停止' : lastError ? '轮询异常(详情见本机日志)' : '轮询中' },
|
|
186
|
+
}
|
|
187
|
+
}
|