@goodandready/dsh-messenger-gateway 0.4.15 → 0.4.17
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.md +4 -0
- package/README.ru.md +4 -0
- package/README.zh.md +1 -1
- package/lib/adapters/index.js +2 -0
- package/lib/adapters/telegram-inbound.js +148 -141
- package/lib/adapters/telegram.js +47 -7
- package/lib/client.js +26 -0
- package/lib/config.js +18 -8
- package/lib/gateway.js +27 -3
- package/lib/index.js +43 -1
- package/lib/proxy.js +669 -0
- package/lib/secret-guard.js +52 -0
- package/lib/telegram-errors.js +0 -0
- package/lib/telegram-format.js +67 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -45,6 +45,8 @@ Talk to your Harness agent from Telegram: text, voice, photos, documents, inline
|
|
|
45
45
|
## Features
|
|
46
46
|
|
|
47
47
|
- Long-poll or webhook Telegram bot
|
|
48
|
+
- Configurable proxy support: HTTP, HTTPS, SOCKS5, and SOCKS5h (`telegram.proxyUrl`)
|
|
49
|
+
- Custom Bot API root URL (`telegram.apiRoot`) for reverse proxies and local Bot API servers
|
|
48
50
|
- Multi-transport support: Telegram, Discord (Webhooks & Bot API), and Slack (Webhooks & Bot API)
|
|
49
51
|
- Allowlist + pairing codes
|
|
50
52
|
- Per-user or per-chat sessions (`sessionScope`)
|
|
@@ -140,6 +142,8 @@ In addition to Telegram, outbound messages can be dispatched to Discord and Slac
|
|
|
140
142
|
- `voiceMode`: `mirror` / `always` / `off` — when to speak replies (also `/voice`)
|
|
141
143
|
- `tts.enabled` / `tts.maxChars` — TTS gate and length cap
|
|
142
144
|
- `notifyBridge` — forward non-messenger web session events to a home
|
|
145
|
+
- `telegram.proxyUrl`: optional HTTP, HTTPS or SOCKS5 proxy URL (`socks5://user:pass@127.0.0.1:1080`, `http://127.0.0.1:8080`); `socks://` and `socks5h://` are aliases. Leave it empty to use `TELEGRAM_PROXY` / `DSH_MESSENGER_TELEGRAM_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` from the environment, use `off`/`none`/`direct` to disable proxying entirely, and `NO_PROXY`/`no_proxy` rules are honoured. The tunnel is implemented with `node:net`/`node:tls` (no extra dependencies) and keeps normal TLS certificate verification for `api.telegram.org`
|
|
146
|
+
- `telegram.apiRoot`: optional custom Telegram Bot API base URL (default: `https://api.telegram.org`), for local Bot API servers or reverse proxies
|
|
143
147
|
- Bot token is a DSH secret field — never commit it
|
|
144
148
|
|
|
145
149
|
## Client UI & Settings Card
|
package/README.ru.md
CHANGED
|
@@ -105,6 +105,10 @@ graph LR
|
|
|
105
105
|
* `/model` — просмотр и переключение активной модели агента;
|
|
106
106
|
* `/help` — список возможностей.
|
|
107
107
|
|
|
108
|
+
### 7. 🌐 Поддержка прокси и кастомного Bot API (`proxy.js`)
|
|
109
|
+
* Маршрутизация запросов к Telegram через прокси: HTTP, HTTPS, SOCKS5 и SOCKS5h (`telegram.proxyUrl`, поддерживаются логин/пароль, `socks://` и `socks5h://` — синонимы). Пустое поле → берётся из окружения (`TELEGRAM_PROXY`, `DSH_MESSENGER_TELEGRAM_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`); `off`/`none`/`direct` отключают прокси, правила `NO_PROXY` соблюдаются. Туннель реализован на `node:net`/`node:tls` без внешних зависимостей, TLS-сертификат `api.telegram.org` проверяется как обычно;
|
|
110
|
+
* Поддержка пользовательского базового адреса API (`telegram.apiRoot`) для локальных серверов Telegram Bot API или обратных прокси (reverse proxy).
|
|
111
|
+
|
|
108
112
|
---
|
|
109
113
|
|
|
110
114
|
## 📦 Быстрая установка
|
package/README.zh.md
CHANGED
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
|
|
40
40
|
**`dsh-messenger-gateway`** 为 **DeepSeek Harness** 智能体提供企业级 Telegram 接入桥梁。
|
|
41
41
|
|
|
42
|
-
除常规对话转发外,本插件全面打通了智能体深度交互能力:**问答交互式内联按钮 (Inline Keyboard)**、**Telegram 论坛话题 (Forum Topics)
|
|
42
|
+
除常规对话转发外,本插件全面打通了智能体深度交互能力:**问答交互式内联按钮 (Inline Keyboard)**、**Telegram 论坛话题 (Forum Topics) 独立会话隔离**、**代理连接支持 (HTTP/HTTPS/SOCKS5 与自定义 apiRoot)**、**单用户工作区目录安全隔离**、**6 位配对码鉴权防护**以及**语音条朗读回复 (TTS)**。
|
|
43
43
|
|
|
44
44
|
```mermaid
|
|
45
45
|
graph LR
|
package/lib/adapters/index.js
CHANGED
|
@@ -23,6 +23,8 @@ export default function createAdapters(deps) {
|
|
|
23
23
|
transport: tg.transport,
|
|
24
24
|
webhookUrl: tg.webhookUrl,
|
|
25
25
|
webhookSecret: tg.webhookSecret,
|
|
26
|
+
proxyUrl: tg.proxyUrl,
|
|
27
|
+
apiRoot: tg.apiRoot,
|
|
26
28
|
quickActions: tg.quickActions !== false,
|
|
27
29
|
artifactPreviews: tg.artifactPreviews !== false,
|
|
28
30
|
media: config.media,
|
|
@@ -1,141 +1,148 @@
|
|
|
1
|
-
import { basename } from 'node:path'
|
|
2
|
-
import {
|
|
3
|
-
IMAGE_EXT_TO_MIME, VIDEO_EXT_TO_MIME, classifyDocument,
|
|
4
|
-
extOf, TELEGRAM_MAX_DOC_BYTES,
|
|
5
|
-
} from '../media.js'
|
|
6
|
-
import { TEXT_INJECT_EXTS } from '../documents.js'
|
|
7
|
-
|
|
8
|
-
export async function extractTelegramInboundMedia(adapter, msg, initialText, maxDocBytes = TELEGRAM_MAX_DOC_BYTES, maxTextInjectBytes = 100 * 1024) {
|
|
9
|
-
let text = initialText || ''
|
|
10
|
-
const attachments = []
|
|
11
|
-
|
|
12
|
-
if (msg.photo?.length) {
|
|
13
|
-
const largest = msg.photo[msg.photo.length - 1]
|
|
14
|
-
const { path, file } = await adapter.downloadByFileId(largest.file_id, 'photo', extOf('', '') || '.jpg')
|
|
15
|
-
const ext = extOf(file.file_path, '') || '.jpg'
|
|
16
|
-
attachments.push({ kind: 'photo', path, mime: IMAGE_EXT_TO_MIME[ext] || 'image/jpeg' })
|
|
17
|
-
}
|
|
18
|
-
if (msg.sticker) {
|
|
19
|
-
const st = msg.sticker
|
|
20
|
-
if (st.is_video) {
|
|
21
|
-
try {
|
|
22
|
-
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker-video', '.webm', st.file_unique_id || '')
|
|
23
|
-
attachments.push({ kind: 'animation', path, mime: 'video/webm', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.webm` })
|
|
24
|
-
if (st.emoji) text = `${text}\n[Video sticker ${st.emoji}]`.trim()
|
|
25
|
-
} catch (e) {
|
|
26
|
-
text = `${text}\n[Video sticker ${st.emoji || ''} (download failed: ${e.message})]`.trim()
|
|
27
|
-
}
|
|
28
|
-
} else if (st.is_animated) {
|
|
29
|
-
try {
|
|
30
|
-
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker-anim', '.tgs', st.file_unique_id || '')
|
|
31
|
-
attachments.push({ kind: 'document', path, mime: 'application/x-tgsticker', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.tgs` })
|
|
32
|
-
if (st.emoji) text = `${text}\n[Animated sticker ${st.emoji}]`.trim()
|
|
33
|
-
} catch (e) {
|
|
34
|
-
text = `${text}\n[Animated sticker ${st.emoji || ''} (download failed: ${e.message})]`.trim()
|
|
35
|
-
}
|
|
36
|
-
} else {
|
|
37
|
-
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker', '.webp', st.file_unique_id || '')
|
|
38
|
-
attachments.push({ kind: 'sticker', path, mime: 'image/webp', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.webp` })
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
if (msg.voice) {
|
|
42
|
-
const { path } = await adapter.downloadByFileId(msg.voice.file_id, 'voice', '.ogg')
|
|
43
|
-
attachments.push({ kind: 'voice', path, mime: 'audio/ogg' })
|
|
44
|
-
}
|
|
45
|
-
if (msg.audio) {
|
|
46
|
-
const ext = extOf(msg.audio.file_name, msg.audio.mime_type) || '.mp3'
|
|
47
|
-
const { path } = await adapter.downloadByFileId(msg.audio.file_id, 'audio', ext, msg.audio.file_name || '')
|
|
48
|
-
attachments.push({ kind: 'audio', path, mime: msg.audio.mime_type || 'audio/mpeg' })
|
|
49
|
-
}
|
|
50
|
-
if (msg.video) {
|
|
51
|
-
const ext = extOf(msg.video.file_name, msg.video.mime_type) || '.mp4'
|
|
52
|
-
if ((msg.video.file_size || 0) > maxDocBytes) {
|
|
53
|
-
text = `${text}\n[Video too large]`.trim()
|
|
54
|
-
} else {
|
|
55
|
-
const { path } = await adapter.downloadByFileId(msg.video.file_id, 'video', ext, msg.video.file_name || '')
|
|
56
|
-
attachments.push({ kind: 'video', path, mime: msg.video.mime_type || VIDEO_EXT_TO_MIME[ext] || 'video/mp4', name: msg.video.file_name || basename(path) })
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
if (msg.video_note) {
|
|
60
|
-
const vn = msg.video_note
|
|
61
|
-
if ((vn.file_size || 0) > maxDocBytes) {
|
|
62
|
-
text = `${text}\n[Video note too large]`.trim()
|
|
63
|
-
} else {
|
|
64
|
-
const { path } = await adapter.downloadByFileId(vn.file_id, 'videonote', '.mp4')
|
|
65
|
-
attachments.push({ kind: 'video', path, mime: 'video/mp4', name: 'video_note.mp4' })
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
if (msg.animation) {
|
|
69
|
-
const an = msg.animation
|
|
70
|
-
const ext = extOf(an.file_name, an.mime_type) || '.mp4'
|
|
71
|
-
if ((an.file_size || 0) > maxDocBytes) {
|
|
72
|
-
text = `${text}\n[Animation too large]`.trim()
|
|
73
|
-
} else {
|
|
74
|
-
const { path } = await adapter.downloadByFileId(an.file_id, 'anim', ext, an.file_name || '')
|
|
75
|
-
attachments.push({ kind: 'animation', path, mime: an.mime_type || 'video/mp4', name: an.file_name || basename(path) })
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
if (msg.document) {
|
|
79
|
-
const doc = msg.document
|
|
80
|
-
const ext = extOf(doc.file_name, doc.mime_type)
|
|
81
|
-
const kind = classifyDocument(ext, doc.mime_type)
|
|
82
|
-
if (doc.file_size > maxDocBytes) {
|
|
83
|
-
text = `${text}\n[Document too large: ${doc.file_name || 'file'}]`.trim()
|
|
84
|
-
} else if (kind === 'unsupported') {
|
|
85
|
-
const { path } = await adapter.downloadByFileId(doc.file_id, 'doc', ext, doc.file_name || '')
|
|
86
|
-
attachments.push({ kind: 'document', path, mime: doc.mime_type || 'application/octet-stream', name: doc.file_name || basename(path) })
|
|
87
|
-
} else {
|
|
88
|
-
const { path, bytes } = await adapter.downloadByFileId(doc.file_id, 'doc', ext, doc.file_name || '')
|
|
89
|
-
if (kind === 'image') attachments.push({ kind: 'photo', path, mime: IMAGE_EXT_TO_MIME[ext] || doc.mime_type || 'image/jpeg', name: doc.file_name })
|
|
90
|
-
else if (kind === 'video') attachments.push({ kind: 'video', path, mime: VIDEO_EXT_TO_MIME[ext] || doc.mime_type || 'video/mp4', name: doc.file_name })
|
|
91
|
-
else if (bytes.length <= maxTextInjectBytes && TEXT_INJECT_EXTS.has(ext)) {
|
|
92
|
-
const body = new TextDecoder('utf-8', { fatal: false }).decode(bytes).slice(0, maxTextInjectBytes)
|
|
93
|
-
text = `${text}\n\n[Document ${doc.file_name}]\n${body}`.trim()
|
|
94
|
-
} else attachments.push({ kind: 'document', path, mime: doc.mime_type || 'application/octet-stream', name: doc.file_name || basename(path) })
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
return { text, attachments }
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export async function probeTelegramHealth(adapter, timeoutMs = 10000) {
|
|
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
|
-
|
|
1
|
+
import { basename } from 'node:path'
|
|
2
|
+
import {
|
|
3
|
+
IMAGE_EXT_TO_MIME, VIDEO_EXT_TO_MIME, classifyDocument,
|
|
4
|
+
extOf, TELEGRAM_MAX_DOC_BYTES,
|
|
5
|
+
} from '../media.js'
|
|
6
|
+
import { TEXT_INJECT_EXTS } from '../documents.js'
|
|
7
|
+
|
|
8
|
+
export async function extractTelegramInboundMedia(adapter, msg, initialText, maxDocBytes = TELEGRAM_MAX_DOC_BYTES, maxTextInjectBytes = 100 * 1024) {
|
|
9
|
+
let text = initialText || ''
|
|
10
|
+
const attachments = []
|
|
11
|
+
|
|
12
|
+
if (msg.photo?.length) {
|
|
13
|
+
const largest = msg.photo[msg.photo.length - 1]
|
|
14
|
+
const { path, file } = await adapter.downloadByFileId(largest.file_id, 'photo', extOf('', '') || '.jpg')
|
|
15
|
+
const ext = extOf(file.file_path, '') || '.jpg'
|
|
16
|
+
attachments.push({ kind: 'photo', path, mime: IMAGE_EXT_TO_MIME[ext] || 'image/jpeg' })
|
|
17
|
+
}
|
|
18
|
+
if (msg.sticker) {
|
|
19
|
+
const st = msg.sticker
|
|
20
|
+
if (st.is_video) {
|
|
21
|
+
try {
|
|
22
|
+
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker-video', '.webm', st.file_unique_id || '')
|
|
23
|
+
attachments.push({ kind: 'animation', path, mime: 'video/webm', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.webm` })
|
|
24
|
+
if (st.emoji) text = `${text}\n[Video sticker ${st.emoji}]`.trim()
|
|
25
|
+
} catch (e) {
|
|
26
|
+
text = `${text}\n[Video sticker ${st.emoji || ''} (download failed: ${e.message})]`.trim()
|
|
27
|
+
}
|
|
28
|
+
} else if (st.is_animated) {
|
|
29
|
+
try {
|
|
30
|
+
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker-anim', '.tgs', st.file_unique_id || '')
|
|
31
|
+
attachments.push({ kind: 'document', path, mime: 'application/x-tgsticker', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.tgs` })
|
|
32
|
+
if (st.emoji) text = `${text}\n[Animated sticker ${st.emoji}]`.trim()
|
|
33
|
+
} catch (e) {
|
|
34
|
+
text = `${text}\n[Animated sticker ${st.emoji || ''} (download failed: ${e.message})]`.trim()
|
|
35
|
+
}
|
|
36
|
+
} else {
|
|
37
|
+
const { path } = await adapter.downloadByFileId(st.file_id, 'sticker', '.webp', st.file_unique_id || '')
|
|
38
|
+
attachments.push({ kind: 'sticker', path, mime: 'image/webp', emoji: st.emoji || '', name: `sticker${st.emoji || ''}.webp` })
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (msg.voice) {
|
|
42
|
+
const { path } = await adapter.downloadByFileId(msg.voice.file_id, 'voice', '.ogg')
|
|
43
|
+
attachments.push({ kind: 'voice', path, mime: 'audio/ogg' })
|
|
44
|
+
}
|
|
45
|
+
if (msg.audio) {
|
|
46
|
+
const ext = extOf(msg.audio.file_name, msg.audio.mime_type) || '.mp3'
|
|
47
|
+
const { path } = await adapter.downloadByFileId(msg.audio.file_id, 'audio', ext, msg.audio.file_name || '')
|
|
48
|
+
attachments.push({ kind: 'audio', path, mime: msg.audio.mime_type || 'audio/mpeg' })
|
|
49
|
+
}
|
|
50
|
+
if (msg.video) {
|
|
51
|
+
const ext = extOf(msg.video.file_name, msg.video.mime_type) || '.mp4'
|
|
52
|
+
if ((msg.video.file_size || 0) > maxDocBytes) {
|
|
53
|
+
text = `${text}\n[Video too large]`.trim()
|
|
54
|
+
} else {
|
|
55
|
+
const { path } = await adapter.downloadByFileId(msg.video.file_id, 'video', ext, msg.video.file_name || '')
|
|
56
|
+
attachments.push({ kind: 'video', path, mime: msg.video.mime_type || VIDEO_EXT_TO_MIME[ext] || 'video/mp4', name: msg.video.file_name || basename(path) })
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (msg.video_note) {
|
|
60
|
+
const vn = msg.video_note
|
|
61
|
+
if ((vn.file_size || 0) > maxDocBytes) {
|
|
62
|
+
text = `${text}\n[Video note too large]`.trim()
|
|
63
|
+
} else {
|
|
64
|
+
const { path } = await adapter.downloadByFileId(vn.file_id, 'videonote', '.mp4')
|
|
65
|
+
attachments.push({ kind: 'video', path, mime: 'video/mp4', name: 'video_note.mp4' })
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (msg.animation) {
|
|
69
|
+
const an = msg.animation
|
|
70
|
+
const ext = extOf(an.file_name, an.mime_type) || '.mp4'
|
|
71
|
+
if ((an.file_size || 0) > maxDocBytes) {
|
|
72
|
+
text = `${text}\n[Animation too large]`.trim()
|
|
73
|
+
} else {
|
|
74
|
+
const { path } = await adapter.downloadByFileId(an.file_id, 'anim', ext, an.file_name || '')
|
|
75
|
+
attachments.push({ kind: 'animation', path, mime: an.mime_type || 'video/mp4', name: an.file_name || basename(path) })
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (msg.document) {
|
|
79
|
+
const doc = msg.document
|
|
80
|
+
const ext = extOf(doc.file_name, doc.mime_type)
|
|
81
|
+
const kind = classifyDocument(ext, doc.mime_type)
|
|
82
|
+
if (doc.file_size > maxDocBytes) {
|
|
83
|
+
text = `${text}\n[Document too large: ${doc.file_name || 'file'}]`.trim()
|
|
84
|
+
} else if (kind === 'unsupported') {
|
|
85
|
+
const { path } = await adapter.downloadByFileId(doc.file_id, 'doc', ext, doc.file_name || '')
|
|
86
|
+
attachments.push({ kind: 'document', path, mime: doc.mime_type || 'application/octet-stream', name: doc.file_name || basename(path) })
|
|
87
|
+
} else {
|
|
88
|
+
const { path, bytes } = await adapter.downloadByFileId(doc.file_id, 'doc', ext, doc.file_name || '')
|
|
89
|
+
if (kind === 'image') attachments.push({ kind: 'photo', path, mime: IMAGE_EXT_TO_MIME[ext] || doc.mime_type || 'image/jpeg', name: doc.file_name })
|
|
90
|
+
else if (kind === 'video') attachments.push({ kind: 'video', path, mime: VIDEO_EXT_TO_MIME[ext] || doc.mime_type || 'video/mp4', name: doc.file_name })
|
|
91
|
+
else if (bytes.length <= maxTextInjectBytes && TEXT_INJECT_EXTS.has(ext)) {
|
|
92
|
+
const body = new TextDecoder('utf-8', { fatal: false }).decode(bytes).slice(0, maxTextInjectBytes)
|
|
93
|
+
text = `${text}\n\n[Document ${doc.file_name}]\n${body}`.trim()
|
|
94
|
+
} else attachments.push({ kind: 'document', path, mime: doc.mime_type || 'application/octet-stream', name: doc.file_name || basename(path) })
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
return { text, attachments }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function probeTelegramHealth(adapter, timeoutMs = 10000) {
|
|
103
|
+
const proxyLabel = adapter?.proxy?.active ? (adapter.proxy.label || '') : ''
|
|
104
|
+
if (!adapter.token) {
|
|
105
|
+
return { ok: false, error: 'Telegram bot token is empty', proxy: proxyLabel }
|
|
106
|
+
}
|
|
107
|
+
const start = Date.now()
|
|
108
|
+
try {
|
|
109
|
+
const apiRoot = adapter.apiRoot || 'https://api.telegram.org'
|
|
110
|
+
const fetchOpts = {
|
|
111
|
+
method: 'POST',
|
|
112
|
+
headers: { 'Content-Type': 'application/json' },
|
|
113
|
+
body: JSON.stringify({}),
|
|
114
|
+
signal: AbortSignal.timeout(Math.max(1000, Number(timeoutMs) || 10000)),
|
|
115
|
+
}
|
|
116
|
+
const apiFetch = typeof adapter.apiFetch === 'function' ? adapter.apiFetch : fetch
|
|
117
|
+
const res = await apiFetch(`${apiRoot}/bot${adapter.token}/getMe`, fetchOpts)
|
|
118
|
+
const latencyMs = Date.now() - start
|
|
119
|
+
const json = await res.json().catch(() => ({}))
|
|
120
|
+
if (!res.ok || json.ok === false) {
|
|
121
|
+
return {
|
|
122
|
+
ok: false,
|
|
123
|
+
latencyMs,
|
|
124
|
+
proxy: proxyLabel,
|
|
125
|
+
error: json.description || `HTTP ${res.status}`,
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const me = json.result || {}
|
|
129
|
+
adapter.botId = Number(me.id) || adapter.botId
|
|
130
|
+
adapter.botUsername = String(me.username || adapter.botUsername)
|
|
131
|
+
return {
|
|
132
|
+
ok: true,
|
|
133
|
+
latencyMs,
|
|
134
|
+
proxy: proxyLabel,
|
|
135
|
+
botId: adapter.botId,
|
|
136
|
+
botUsername: adapter.botUsername,
|
|
137
|
+
firstName: me.first_name || '',
|
|
138
|
+
}
|
|
139
|
+
} catch (err) {
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
latencyMs: Date.now() - start,
|
|
143
|
+
proxy: proxyLabel,
|
|
144
|
+
error: err instanceof Error ? err.message : String(err),
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
package/lib/adapters/telegram.js
CHANGED
|
@@ -13,10 +13,25 @@ import {
|
|
|
13
13
|
} from '../groups.js'
|
|
14
14
|
import { isResendSafeNetworkError, isPollingConflict, isTopicGoneError, computePollBackoffMs } from '../telegram-errors.js'
|
|
15
15
|
import { extractTelegramInboundMedia, probeTelegramHealth } from './telegram-inbound.js'
|
|
16
|
+
import { createProxiedFetch, describeProxy, normalizeApiRoot } from '../proxy.js'
|
|
16
17
|
|
|
17
|
-
const API = 'https://api.telegram.org'
|
|
18
18
|
const TELEGRAM_MAX = 4096
|
|
19
19
|
|
|
20
|
+
// Telegram повторно отдаёт апдейты, которые не были подтверждены более высоким
|
|
21
|
+
// offset (перезапуск адаптера, конфликт двух getUpdates, повторная доставка).
|
|
22
|
+
// Держим id обработанных апдейтов на уровне модуля — тогда даже при нескольких
|
|
23
|
+
// циклах опроса команда не будет выполнена дважды.
|
|
24
|
+
const PROCESSED_UPDATE_LIMIT = 1000
|
|
25
|
+
const processedUpdateIds = new Set()
|
|
26
|
+
|
|
27
|
+
function rememberUpdate(id) {
|
|
28
|
+
processedUpdateIds.add(id)
|
|
29
|
+
if (processedUpdateIds.size > PROCESSED_UPDATE_LIMIT) {
|
|
30
|
+
const oldest = processedUpdateIds.values().next().value
|
|
31
|
+
processedUpdateIds.delete(oldest)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
20
35
|
import { buildQuickActionsKeyboard, REMOVE_REPLY_KEYBOARD } from '../commands.js'
|
|
21
36
|
export { buildQuickActionsKeyboard, REMOVE_REPLY_KEYBOARD }
|
|
22
37
|
|
|
@@ -55,6 +70,20 @@ export class TelegramAdapter {
|
|
|
55
70
|
this.pollTimer = undefined
|
|
56
71
|
this.botId = 0
|
|
57
72
|
this.botUsername = ''
|
|
73
|
+
this.apiRoot = normalizeApiRoot(opts.apiRoot)
|
|
74
|
+
this.proxyUrl = String(opts.proxyUrl || '').trim()
|
|
75
|
+
// Прокси для Bot API: http(s)-CONNECT и SOCKS5 (в т.ч. с логином/паролем),
|
|
76
|
+
// без внешних зависимостей. Пустая настройка → значение из окружения
|
|
77
|
+
// (TELEGRAM_PROXY / DSH_MESSENGER_TELEGRAM_PROXY / HTTPS_PROXY / ALL_PROXY).
|
|
78
|
+
this.proxy = describeProxy(this.proxyUrl)
|
|
79
|
+
try {
|
|
80
|
+
this.apiFetch = createProxiedFetch(this.proxyUrl, { logger: this.logger }) || fetch
|
|
81
|
+
if (this.proxy.active) this.logger?.info?.(`dsh-messenger-gateway: telegram via proxy ${this.proxy.label}`)
|
|
82
|
+
} catch (err) {
|
|
83
|
+
this.proxy = { ...this.proxy, active: false, error: err.message }
|
|
84
|
+
this.apiFetch = fetch
|
|
85
|
+
this.logger?.error?.(`dsh-messenger-gateway: telegram proxy is invalid, using direct connection: ${err.message}`)
|
|
86
|
+
}
|
|
58
87
|
}
|
|
59
88
|
|
|
60
89
|
setAllowedUserIds(ids) {
|
|
@@ -63,13 +92,14 @@ export class TelegramAdapter {
|
|
|
63
92
|
|
|
64
93
|
async call(method, params = {}) {
|
|
65
94
|
const timeoutMs = (this.timeoutSeconds * 1000) + 15000
|
|
66
|
-
const
|
|
95
|
+
const fetchOpts = {
|
|
67
96
|
method: 'POST',
|
|
68
97
|
headers: { 'Content-Type': 'application/json' },
|
|
69
98
|
body: JSON.stringify(params),
|
|
70
99
|
keepalive: true,
|
|
71
100
|
signal: AbortSignal.timeout(timeoutMs),
|
|
72
|
-
}
|
|
101
|
+
}
|
|
102
|
+
const res = await this.apiFetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
|
|
73
103
|
const json = await res.json().catch(() => ({}))
|
|
74
104
|
if (!res.ok || json.ok === false) throw new Error(`telegram ${method}: ${json.description || res.status}`)
|
|
75
105
|
return json.result
|
|
@@ -77,12 +107,13 @@ export class TelegramAdapter {
|
|
|
77
107
|
|
|
78
108
|
async callMultipart(method, form) {
|
|
79
109
|
const timeoutMs = (this.timeoutSeconds * 1000) + 30000
|
|
80
|
-
const
|
|
110
|
+
const fetchOpts = {
|
|
81
111
|
method: 'POST',
|
|
82
112
|
body: form,
|
|
83
113
|
keepalive: true,
|
|
84
114
|
signal: AbortSignal.timeout(timeoutMs),
|
|
85
|
-
}
|
|
115
|
+
}
|
|
116
|
+
const res = await this.apiFetch(`${this.apiRoot}/bot${this.token}/${method}`, fetchOpts)
|
|
86
117
|
const json = await res.json().catch(() => ({}))
|
|
87
118
|
if (!res.ok || json.ok === false) throw new Error(`telegram ${method}: ${json.description || res.status}`)
|
|
88
119
|
return json.result
|
|
@@ -110,10 +141,11 @@ export class TelegramAdapter {
|
|
|
110
141
|
|
|
111
142
|
async downloadFile(filePath) {
|
|
112
143
|
const timeoutMs = (this.timeoutSeconds * 1000) + 30000
|
|
113
|
-
const
|
|
144
|
+
const fetchOpts = {
|
|
114
145
|
keepalive: true,
|
|
115
146
|
signal: AbortSignal.timeout(timeoutMs),
|
|
116
|
-
}
|
|
147
|
+
}
|
|
148
|
+
const res = await this.apiFetch(`${this.apiRoot}/file/bot${this.token}/${filePath}`, fetchOpts)
|
|
117
149
|
if (!res.ok) throw new Error(`telegram download HTTP ${res.status}`)
|
|
118
150
|
return new Uint8Array(await res.arrayBuffer())
|
|
119
151
|
}
|
|
@@ -172,6 +204,7 @@ export class TelegramAdapter {
|
|
|
172
204
|
} catch (err) {
|
|
173
205
|
this.logger?.warn?.(`dsh-messenger-gateway: telegram setMyCommands: ${err.message}`)
|
|
174
206
|
}
|
|
207
|
+
if (this.stopped) return
|
|
175
208
|
if (this.transport === 'webhook') {
|
|
176
209
|
if (!this.webhookUrl) throw new Error('telegram webhookUrl is required for webhook transport')
|
|
177
210
|
if (!this.webhookSecret) throw new Error('telegram webhookSecret is required for webhook transport')
|
|
@@ -195,6 +228,8 @@ export class TelegramAdapter {
|
|
|
195
228
|
} catch (err) {
|
|
196
229
|
this.logger?.debug?.('telegram deleteWebhook failed (safe to ignore):', err?.message || err)
|
|
197
230
|
}
|
|
231
|
+
// start() мог быть прерван stop() за время сетевых вызовов выше.
|
|
232
|
+
if (this.stopped) return
|
|
198
233
|
this.poll()
|
|
199
234
|
}
|
|
200
235
|
|
|
@@ -226,6 +261,11 @@ export class TelegramAdapter {
|
|
|
226
261
|
this.pollErrorCount = 0
|
|
227
262
|
for (const update of updates || []) {
|
|
228
263
|
this.offset = Math.max(this.offset, update.update_id + 1)
|
|
264
|
+
if (processedUpdateIds.has(update.update_id)) {
|
|
265
|
+
this.logger?.debug?.(`telegram: skipping already handled update ${update.update_id}`)
|
|
266
|
+
continue
|
|
267
|
+
}
|
|
268
|
+
rememberUpdate(update.update_id)
|
|
229
269
|
await this.dispatchUpdate(update)
|
|
230
270
|
}
|
|
231
271
|
} catch (e) {
|
package/lib/client.js
CHANGED
|
@@ -105,6 +105,10 @@ window.__ModuleLoader__.load({
|
|
|
105
105
|
webhookSecretHint: 'Leave empty to keep current configured secret',
|
|
106
106
|
webhookSecretConfigured: 'Secret set',
|
|
107
107
|
webhookSecretRequired: 'Secret required',
|
|
108
|
+
proxyUrl: 'Proxy URL (HTTP, HTTPS, SOCKS5)',
|
|
109
|
+
proxyUrlHint: 'Optional proxy for Telegram API requests (e.g. socks5://127.0.0.1:1080 or http://127.0.0.1:8080).',
|
|
110
|
+
apiRoot: 'Custom Telegram Bot API Base URL',
|
|
111
|
+
apiRootHint: 'Custom API root for reverse proxies or local Bot API servers. Default: https://api.telegram.org',
|
|
108
112
|
sessionScope: 'Group Session Scope',
|
|
109
113
|
sessionScopeChat: 'Shared per chat/topic',
|
|
110
114
|
sessionScopeUser: 'Per-user session (recommended)',
|
|
@@ -248,6 +252,10 @@ window.__ModuleLoader__.load({
|
|
|
248
252
|
webhookSecretHint: '留空保持当前配置的密钥',
|
|
249
253
|
webhookSecretConfigured: '密钥已设置',
|
|
250
254
|
webhookSecretRequired: '必须设置密钥',
|
|
255
|
+
proxyUrl: '代理地址 (HTTP, HTTPS, SOCKS5)',
|
|
256
|
+
proxyUrlHint: 'Telegram API 请求的可选代理(例如 socks5://127.0.0.1:1080 或 http://127.0.0.1:8080)。',
|
|
257
|
+
apiRoot: '自定义 Telegram Bot API 地址',
|
|
258
|
+
apiRootHint: '用于反向代理或本地 Bot API 服务器的自定义根地址。默认:https://api.telegram.org',
|
|
251
259
|
sessionScope: '群组会话范围',
|
|
252
260
|
sessionScopeChat: '每个聊天/话题共享',
|
|
253
261
|
sessionScopeUser: '每用户独立会话 (推荐)',
|
|
@@ -510,6 +518,8 @@ window.__ModuleLoader__.load({
|
|
|
510
518
|
alerts: t.alerts || { enabled: false, chatId: '', threadId: 0, home: '', events: ['error', 'pairing'] },
|
|
511
519
|
botToken: t.botToken || '',
|
|
512
520
|
webhookSecret: t.webhookSecret || '',
|
|
521
|
+
proxyUrl: t.proxyUrl || '',
|
|
522
|
+
apiRoot: t.apiRoot || '',
|
|
513
523
|
},
|
|
514
524
|
discord: {
|
|
515
525
|
enabled: d.enabled === true,
|
|
@@ -1467,6 +1477,22 @@ window.__ModuleLoader__.load({
|
|
|
1467
1477
|
onChange: (e) => setWebhookSecret(e.target.value),
|
|
1468
1478
|
})
|
|
1469
1479
|
),
|
|
1480
|
+
React.createElement(Field, { label: t('proxyUrl'), hint: t('proxyUrlHint') },
|
|
1481
|
+
React.createElement('input', {
|
|
1482
|
+
className: 'msgw-input',
|
|
1483
|
+
value: cfg.telegram?.proxyUrl || '',
|
|
1484
|
+
placeholder: 'socks5://127.0.0.1:1080 or http://127.0.0.1:8080',
|
|
1485
|
+
onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, proxyUrl: e.target.value } }),
|
|
1486
|
+
})
|
|
1487
|
+
),
|
|
1488
|
+
React.createElement(Field, { label: t('apiRoot'), hint: t('apiRootHint') },
|
|
1489
|
+
React.createElement('input', {
|
|
1490
|
+
className: 'msgw-input',
|
|
1491
|
+
value: cfg.telegram?.apiRoot || '',
|
|
1492
|
+
placeholder: 'https://api.telegram.org',
|
|
1493
|
+
onChange: (e) => setCfg({ ...cfg, telegram: { ...cfg.telegram, apiRoot: e.target.value } }),
|
|
1494
|
+
})
|
|
1495
|
+
),
|
|
1470
1496
|
React.createElement(Field, { label: t('pollTimeout') },
|
|
1471
1497
|
React.createElement('input', {
|
|
1472
1498
|
type: 'number',
|
package/lib/config.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import z from '@deepseek-ai/schemastery'
|
|
2
2
|
|
|
3
|
+
// DSH persists plugin settings (into the profile patch) only for schema paths it
|
|
4
|
+
// can treat as live-editable: every write goes through `volatileForm(schema)` in
|
|
5
|
+
// @deepseek-ai/dsh-settings and is rejected with
|
|
6
|
+
// `Config field "<path>" is not volatile` otherwise. Only `enabled` and
|
|
7
|
+
// `internalBaseURL` were volatile, so the settings card could not save anything
|
|
8
|
+
// else. The configurable sections are declared volatile as a whole — the card
|
|
9
|
+
// edits them as live values and the gateway restarts its adapters on change.
|
|
10
|
+
|
|
3
11
|
const HomeEntry = z.object({
|
|
4
12
|
name: z.string().default('default'),
|
|
5
13
|
chatId: z.union([z.number(), z.string()]),
|
|
@@ -9,7 +17,7 @@ const HomeEntry = z.object({
|
|
|
9
17
|
export const PluginConfig = z.object({
|
|
10
18
|
enabled: z.boolean().volatile().default(true),
|
|
11
19
|
internalBaseURL: z.string().volatile().default('').description('Internal base URL for host services; if omitted, resolved dynamically from webServer port or falls back to http://127.0.0.1:3080'),
|
|
12
|
-
defaultLocale: z.union([z.const('en'), z.const('zh')]).default('en').description('Default language for bot messages and notifications (en, zh)'),
|
|
20
|
+
defaultLocale: z.union([z.const('en'), z.const('zh')]).volatile().default('en').description('Default language for bot messages and notifications (en, zh)'),
|
|
13
21
|
telegram: z.object({
|
|
14
22
|
enabled: z.boolean().default(false),
|
|
15
23
|
botToken: z.string().role('secret').default(''),
|
|
@@ -39,6 +47,8 @@ export const PluginConfig = z.object({
|
|
|
39
47
|
webhookUrl: z.string().default(''),
|
|
40
48
|
webhookSecret: z.string().role('secret').default(''),
|
|
41
49
|
webhookPath: z.string().default('/dsh-messenger-gateway/telegram/webhook'),
|
|
50
|
+
proxyUrl: z.string().default('').description('Proxy for Telegram Bot API calls: http(s)://[user:pass@]host:port or socks5://[user:pass@]host:port (socks5h/socks are aliases). Empty = take from the environment (TELEGRAM_PROXY/HTTPS_PROXY/ALL_PROXY); off/none/direct = never use a proxy'),
|
|
51
|
+
apiRoot: z.string().default('').description('Custom Telegram Bot API root URL (default: https://api.telegram.org)'),
|
|
42
52
|
voiceMode: z.union([z.const('mirror'), z.const('always'), z.const('off')]).default('mirror')
|
|
43
53
|
.description('mirror: TTS when inbound was voice; always/off override (per-user /voice wins)'),
|
|
44
54
|
quickActions: z.boolean().default(false).description('Show quick actions keyboard in Telegram (/new, /stop, /voice, /status)'),
|
|
@@ -62,32 +72,32 @@ export const PluginConfig = z.object({
|
|
|
62
72
|
}).default({ enabled: false }),
|
|
63
73
|
forumMirrorChatId: z.union([z.number(), z.string()]).default(''),
|
|
64
74
|
forumMirrorEnabled: z.boolean().default(false),
|
|
65
|
-
}),
|
|
75
|
+
}).volatile(),
|
|
66
76
|
discord: z.object({
|
|
67
77
|
enabled: z.boolean().default(false),
|
|
68
78
|
botToken: z.string().role('secret').default(''),
|
|
69
79
|
webhookUrl: z.string().default(''),
|
|
70
|
-
}).default({ enabled: false }),
|
|
80
|
+
}).default({ enabled: false }).volatile(),
|
|
71
81
|
slack: z.object({
|
|
72
82
|
enabled: z.boolean().default(false),
|
|
73
83
|
botToken: z.string().role('secret').default(''),
|
|
74
84
|
webhookUrl: z.string().default(''),
|
|
75
|
-
}).default({ enabled: false }),
|
|
85
|
+
}).default({ enabled: false }).volatile(),
|
|
76
86
|
webhooks: z.object({
|
|
77
87
|
enabled: z.boolean().default(true),
|
|
78
88
|
secret: z.string().role('secret').default(''),
|
|
79
|
-
}).default({ enabled: true }),
|
|
89
|
+
}).default({ enabled: true }).volatile(),
|
|
80
90
|
media: z.object({
|
|
81
91
|
cacheDir: z.string().default(''),
|
|
82
92
|
maxDocBytes: z.number().default(20 * 1024 * 1024),
|
|
83
93
|
maxTextInjectBytes: z.number().default(100 * 1024),
|
|
84
94
|
maxImageBytes: z.number().default(20 * 1024 * 1024),
|
|
85
|
-
}),
|
|
95
|
+
}).volatile(),
|
|
86
96
|
tts: z.object({
|
|
87
97
|
enabled: z.boolean().default(false),
|
|
88
98
|
maxChars: z.number().default(4000),
|
|
89
99
|
voiceSummary: z.boolean().default(false).description('Speak concise TL;DR summary while full text is sent to chat'),
|
|
90
|
-
}),
|
|
100
|
+
}).volatile(),
|
|
91
101
|
agent: z.object({
|
|
92
102
|
provider: z.string().default(''),
|
|
93
103
|
model: z.string().default(''),
|
|
@@ -99,7 +109,7 @@ export const PluginConfig = z.object({
|
|
|
99
109
|
photoOnlyMode: z.union([z.const('prompt'), z.const('run')]).default('prompt'),
|
|
100
110
|
sessionScope: z.union([z.const('chat'), z.const('user')]).default('user')
|
|
101
111
|
.description('In groups: user = per-user session; chat = shared session for the chat/topic'),
|
|
102
|
-
}),
|
|
112
|
+
}).volatile(),
|
|
103
113
|
})
|
|
104
114
|
|
|
105
115
|
export const Config = PluginConfig
|