opc-agent 4.1.0 → 4.1.2
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/.github/ISSUE_TEMPLATE/bug_report.md +20 -20
- package/.github/ISSUE_TEMPLATE/feature_request.md +14 -14
- package/.github/PULL_REQUEST_TEMPLATE.md +13 -13
- package/CHANGELOG.md +48 -48
- package/CONTRIBUTING.md +36 -36
- package/README.zh-CN.md +497 -497
- package/USABILITY-ISSUES.md +73 -0
- package/dist/channels/web.js +8 -2
- package/dist/channels/wechat.js +6 -6
- package/dist/cli.js +200 -85
- package/dist/core/runtime.js +37 -15
- package/dist/deploy/index.js +56 -56
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +105 -10
- package/dist/memory/deepbrain.d.ts +1 -1
- package/dist/memory/deepbrain.js +95 -4
- package/dist/scheduler/cron-engine.js +3 -36
- package/dist/studio/server.js +30 -1
- package/dist/studio-ui/index.html +230 -10
- package/dist/ui/components.js +105 -105
- package/examples/README.md +22 -22
- package/examples/basic-agent.ts +90 -90
- package/examples/brain-integration.ts +71 -71
- package/examples/multi-channel.ts +74 -74
- package/fix-sidebar.mjs +188 -188
- package/install.ps1 +154 -154
- package/install.sh +164 -164
- package/package.json +1 -1
- package/scripts/install.ps1 +31 -31
- package/scripts/install.sh +40 -40
- package/serve-studio.js +13 -13
- package/serve-test.js +25 -25
- package/src/channels/dingtalk.ts +46 -46
- package/src/channels/email.ts +351 -351
- package/src/channels/feishu.ts +349 -349
- package/src/channels/googlechat.ts +42 -42
- package/src/channels/imessage.ts +31 -31
- package/src/channels/irc.ts +82 -82
- package/src/channels/line.ts +32 -32
- package/src/channels/matrix.ts +33 -33
- package/src/channels/mattermost.ts +57 -57
- package/src/channels/msteams.ts +32 -32
- package/src/channels/nostr.ts +32 -32
- package/src/channels/qq.ts +33 -33
- package/src/channels/signal.ts +32 -32
- package/src/channels/sms.ts +33 -33
- package/src/channels/telegram.ts +616 -616
- package/src/channels/twitch.ts +65 -65
- package/src/channels/voice-call.ts +100 -100
- package/src/channels/web.ts +8 -2
- package/src/channels/websocket.ts +399 -399
- package/src/channels/wechat.ts +329 -329
- package/src/channels/whatsapp.ts +32 -32
- package/src/cli/chat.ts +99 -99
- package/src/cli/setup.ts +314 -314
- package/src/cli.ts +195 -92
- package/src/core/agent.ts +476 -476
- package/src/core/api-server.ts +277 -277
- package/src/core/audio.ts +98 -98
- package/src/core/collaboration.ts +275 -275
- package/src/core/context-discovery.ts +85 -85
- package/src/core/context-refs.ts +140 -140
- package/src/core/gateway.ts +106 -106
- package/src/core/heartbeat.ts +51 -51
- package/src/core/hooks.ts +105 -105
- package/src/core/ide-bridge.ts +133 -133
- package/src/core/node-network.ts +86 -86
- package/src/core/profiles.ts +122 -122
- package/src/core/runtime.ts +25 -0
- package/src/core/scheduler.ts +187 -187
- package/src/core/session-manager.ts +137 -137
- package/src/core/subagent.ts +98 -98
- package/src/core/vision.ts +180 -180
- package/src/core/workflow-graph.ts +365 -365
- package/src/daemon.ts +96 -96
- package/src/deploy/index.ts +255 -255
- package/src/doctor.ts +98 -11
- package/src/eval/index.ts +211 -211
- package/src/eval/suites/basic.json +16 -16
- package/src/eval/suites/memory.json +12 -12
- package/src/eval/suites/safety.json +14 -14
- package/src/hub/brain-seed.ts +54 -54
- package/src/hub/client.ts +60 -60
- package/src/mcp/servers/calculator-mcp.ts +65 -65
- package/src/mcp/servers/crypto-mcp.ts +73 -73
- package/src/mcp/servers/database-mcp.ts +72 -72
- package/src/mcp/servers/datetime-mcp.ts +69 -69
- package/src/mcp/servers/filesystem.ts +66 -66
- package/src/mcp/servers/github-mcp.ts +58 -58
- package/src/mcp/servers/index.ts +63 -63
- package/src/mcp/servers/json-mcp.ts +102 -102
- package/src/mcp/servers/memory-mcp.ts +56 -56
- package/src/mcp/servers/regex-mcp.ts +53 -53
- package/src/mcp/servers/web-mcp.ts +49 -49
- package/src/memory/context-compressor.ts +189 -189
- package/src/memory/deepbrain.ts +99 -5
- package/src/memory/seed-loader.ts +212 -212
- package/src/memory/user-profiler.ts +215 -215
- package/src/plugins/content-filter.ts +23 -23
- package/src/plugins/logger.ts +18 -18
- package/src/plugins/rate-limiter.ts +38 -38
- package/src/protocols/a2a/client.ts +132 -132
- package/src/protocols/a2a/index.ts +8 -8
- package/src/protocols/a2a/server.ts +333 -333
- package/src/protocols/a2a/types.ts +88 -88
- package/src/protocols/a2a/utils.ts +50 -50
- package/src/protocols/agui/client.ts +83 -83
- package/src/protocols/agui/index.ts +4 -4
- package/src/protocols/agui/server.ts +218 -218
- package/src/protocols/agui/types.ts +153 -153
- package/src/protocols/index.ts +2 -2
- package/src/protocols/mcp/agent-tools.ts +134 -134
- package/src/protocols/mcp/index.ts +8 -8
- package/src/protocols/mcp/server.ts +262 -262
- package/src/protocols/mcp/types.ts +69 -69
- package/src/providers/index.ts +632 -632
- package/src/publish/index.ts +376 -376
- package/src/scheduler/cron-engine.ts +191 -191
- package/src/scheduler/index.ts +2 -2
- package/src/schema/oad.ts +217 -217
- package/src/security/approval.ts +131 -131
- package/src/security/approvals.ts +143 -143
- package/src/security/elevated.ts +105 -105
- package/src/security/guardrails.ts +248 -248
- package/src/security/index.ts +9 -9
- package/src/security/keys.ts +87 -87
- package/src/security/secrets.ts +129 -129
- package/src/skills/builtin/index.ts +408 -408
- package/src/skills/marketplace.ts +113 -113
- package/src/skills/types.ts +42 -42
- package/src/studio/server.ts +31 -1
- package/src/studio/templates-data.ts +178 -178
- package/src/studio-ui/index.html +230 -10
- package/src/telemetry/index.ts +324 -324
- package/src/tools/builtin/browser.ts +299 -299
- package/src/tools/builtin/datetime.ts +41 -41
- package/src/tools/builtin/file.ts +107 -107
- package/src/tools/builtin/home-assistant.ts +116 -116
- package/src/tools/builtin/rl-tools.ts +243 -243
- package/src/tools/builtin/shell.ts +43 -43
- package/src/tools/builtin/vision.ts +64 -64
- package/src/tools/builtin/web-search.ts +126 -126
- package/src/tools/builtin/web.ts +35 -35
- package/src/tools/document-processor.ts +213 -213
- package/src/tools/image-generator.ts +150 -150
- package/src/tools/integrations/calendar.ts +73 -73
- package/src/tools/integrations/code-exec.ts +39 -39
- package/src/tools/integrations/csv-analyzer.ts +92 -92
- package/src/tools/integrations/database.ts +44 -44
- package/src/tools/integrations/email-send.ts +76 -76
- package/src/tools/integrations/git-tool.ts +42 -42
- package/src/tools/integrations/github-tool.ts +76 -76
- package/src/tools/integrations/image-gen.ts +56 -56
- package/src/tools/integrations/index.ts +92 -92
- package/src/tools/integrations/jira.ts +83 -83
- package/src/tools/integrations/notion.ts +71 -71
- package/src/tools/integrations/npm-tool.ts +48 -48
- package/src/tools/integrations/pdf-reader.ts +58 -58
- package/src/tools/integrations/slack.ts +65 -65
- package/src/tools/integrations/summarizer.ts +49 -49
- package/src/tools/integrations/translator.ts +48 -48
- package/src/tools/integrations/trello.ts +60 -60
- package/src/tools/integrations/vector-search.ts +42 -42
- package/src/tools/integrations/web-scraper.ts +47 -47
- package/src/tools/integrations/web-search.ts +58 -58
- package/src/tools/integrations/webhook.ts +38 -38
- package/src/tools/mcp-client.ts +131 -131
- package/src/tools/web-scraper.ts +179 -179
- package/src/tools/web-search.ts +180 -180
- package/src/ui/components.ts +127 -127
- package/srv-out.txt +1 -1
- package/templates/ecommerce-assistant/README.md +45 -45
- package/templates/ecommerce-assistant/oad.yaml +47 -47
- package/templates/tech-support/README.md +43 -43
- package/templates/tech-support/oad.yaml +45 -45
- package/test-agent/Dockerfile +9 -9
- package/test-agent/README.md +50 -50
- package/test-agent/agent.yaml +23 -23
- package/test-agent/docker-compose.yml +11 -11
- package/test-agent/oad.yaml +31 -31
- package/test-agent/package-lock.json +1492 -1492
- package/test-agent/package.json +17 -17
- package/test-agent/src/index.ts +24 -24
- package/test-agent/src/skills/echo.ts +15 -15
- package/test-agent/tsconfig.json +24 -24
- package/test-full.js +43 -43
- package/test-sidebar.js +22 -22
- package/test-studio3.js +75 -75
- package/test-studio4.js +41 -41
- package/tests/a2a-protocol.test.ts +285 -285
- package/tests/agui-protocol.test.ts +246 -246
- package/tests/api-server.test.ts +148 -148
- package/tests/approvals.test.ts +89 -89
- package/tests/audio.test.ts +40 -40
- package/tests/brain-seed-extended.test.ts +490 -490
- package/tests/brain-seed.test.ts +239 -239
- package/tests/browser.test.ts +179 -179
- package/tests/channels/discord.test.ts +79 -79
- package/tests/channels/email.test.ts +148 -148
- package/tests/channels/feishu.test.ts +123 -123
- package/tests/channels/telegram.test.ts +129 -129
- package/tests/channels/websocket.test.ts +53 -53
- package/tests/channels/wechat.test.ts +170 -170
- package/tests/channels-extra.test.ts +45 -45
- package/tests/chat-cli.test.ts +160 -160
- package/tests/cli.test.ts +46 -46
- package/tests/context-compressor.test.ts +172 -172
- package/tests/context-refs.test.ts +121 -121
- package/tests/cron-engine.test.ts +101 -101
- package/tests/daemon.test.ts +135 -135
- package/tests/deepbrain-wire.test.ts +234 -234
- package/tests/deploy-and-dag.test.ts +196 -196
- package/tests/doctor.test.ts +38 -38
- package/tests/document-processor.test.ts +69 -69
- package/tests/e2e-nocode.test.ts +442 -442
- package/tests/elevated.test.ts +69 -69
- package/tests/eval.test.ts +173 -173
- package/tests/gateway.test.ts +63 -63
- package/tests/guardrails.test.ts +177 -177
- package/tests/home-assistant.test.ts +40 -40
- package/tests/hooks.test.ts +79 -79
- package/tests/ide-bridge.test.ts +38 -38
- package/tests/image-generator.test.ts +84 -84
- package/tests/init-role.test.ts +124 -124
- package/tests/integrations.test.ts +249 -249
- package/tests/mcp-client.test.ts +92 -92
- package/tests/mcp-server.test.ts +178 -178
- package/tests/mcp-servers.test.ts +260 -260
- package/tests/node-network.test.ts +74 -74
- package/tests/plugin-a2a-enhanced.test.ts +230 -230
- package/tests/profiles.test.ts +61 -61
- package/tests/publish.test.ts +231 -231
- package/tests/rl-tools.test.ts +93 -93
- package/tests/sandbox-manager.test.ts +46 -46
- package/tests/scheduler.test.ts +200 -200
- package/tests/secrets.test.ts +107 -107
- package/tests/security-enhanced.test.ts +233 -233
- package/tests/settings-api.test.ts +148 -148
- package/tests/setup.test.ts +73 -73
- package/tests/subagent.test.ts +193 -193
- package/tests/telegram-discord.test.ts +60 -60
- package/tests/telemetry.test.ts +186 -186
- package/tests/user-profiler.test.ts +169 -169
- package/tests/v090-features.test.ts +254 -254
- package/tests/vision.test.ts +61 -61
- package/tests/voice-call.test.ts +47 -47
- package/tests/voice-enhanced.test.ts +169 -169
- package/tests/voice-interaction.test.ts +38 -38
- package/tests/web-search.test.ts +155 -155
- package/tests/workflow-graph.test.ts +279 -279
- package/tutorial/customer-service-agent/README.md +612 -612
- package/tutorial/customer-service-agent/SOUL.md +26 -26
- package/tutorial/customer-service-agent/agent.yaml +63 -63
- package/tutorial/customer-service-agent/package.json +19 -19
- package/tutorial/customer-service-agent/src/index.ts +69 -69
- package/tutorial/customer-service-agent/src/skills/faq.ts +27 -27
- package/tutorial/customer-service-agent/src/skills/ticket.ts +22 -22
- package/tutorial/customer-service-agent/tsconfig.json +14 -14
package/src/channels/telegram.ts
CHANGED
|
@@ -1,616 +1,616 @@
|
|
|
1
|
-
import type { Message } from '../core/types';
|
|
2
|
-
import { BaseChannel } from './index';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Telegram channel — production-quality Telegram bot integration.
|
|
6
|
-
*
|
|
7
|
-
* Features (aligned with OpenClaw):
|
|
8
|
-
* - Live stream preview (sendMessage + editMessageText)
|
|
9
|
-
* - Ack reaction on message receipt
|
|
10
|
-
* - Typing indicator throughout processing
|
|
11
|
-
* - HTML parse mode with Markdown fallback
|
|
12
|
-
* - Smart text chunking (paragraph-aware)
|
|
13
|
-
* - /start, /help, /status commands
|
|
14
|
-
* - Photo/document caption handling
|
|
15
|
-
* - Callback query (inline button) support
|
|
16
|
-
* - Reply threading
|
|
17
|
-
* - Error recovery with plain-text fallback
|
|
18
|
-
* - Forum topic support
|
|
19
|
-
* - Group mention filtering
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
export interface TelegramChannelConfig {
|
|
23
|
-
token?: string;
|
|
24
|
-
mode?: 'polling' | 'webhook';
|
|
25
|
-
webhookUrl?: string;
|
|
26
|
-
webhookSecret?: string;
|
|
27
|
-
port?: number;
|
|
28
|
-
// Feature flags
|
|
29
|
-
streaming?: boolean | 'off' | 'partial';
|
|
30
|
-
ackReaction?: string; // emoji to react with on receipt, e.g. "👀"
|
|
31
|
-
linkPreview?: boolean;
|
|
32
|
-
textChunkLimit?: number;
|
|
33
|
-
requireMention?: boolean; // for groups
|
|
34
|
-
botUsername?: string; // for mention detection
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export class TelegramChannel extends BaseChannel {
|
|
38
|
-
readonly type = 'telegram';
|
|
39
|
-
private token: string;
|
|
40
|
-
private mode: 'polling' | 'webhook';
|
|
41
|
-
private webhookUrl?: string;
|
|
42
|
-
private webhookSecret?: string;
|
|
43
|
-
private port: number;
|
|
44
|
-
private botUsername: string = '';
|
|
45
|
-
private botInfo: any = null;
|
|
46
|
-
|
|
47
|
-
// Config
|
|
48
|
-
private streamingEnabled: boolean;
|
|
49
|
-
private ackReaction: string;
|
|
50
|
-
private linkPreview: boolean;
|
|
51
|
-
private textChunkLimit: number;
|
|
52
|
-
private requireMention: boolean;
|
|
53
|
-
|
|
54
|
-
// Polling state
|
|
55
|
-
private offset: number = 0;
|
|
56
|
-
private polling: boolean = false;
|
|
57
|
-
|
|
58
|
-
// Webhook state
|
|
59
|
-
private server: import('http').Server | null = null;
|
|
60
|
-
|
|
61
|
-
// Stream handler — set by runtime when provider supports streaming
|
|
62
|
-
private streamHandler?: (msg: Message) => AsyncIterable<string>;
|
|
63
|
-
|
|
64
|
-
constructor(config: TelegramChannelConfig = {}) {
|
|
65
|
-
super();
|
|
66
|
-
this.token = config.token ?? process.env.TELEGRAM_BOT_TOKEN ?? '';
|
|
67
|
-
this.mode = config.mode ?? 'polling';
|
|
68
|
-
this.webhookUrl = config.webhookUrl;
|
|
69
|
-
this.webhookSecret = config.webhookSecret;
|
|
70
|
-
this.port = config.port ?? 3001;
|
|
71
|
-
|
|
72
|
-
// Feature config
|
|
73
|
-
this.streamingEnabled = config.streaming !== false && config.streaming !== 'off';
|
|
74
|
-
this.ackReaction = config.ackReaction ?? '👀';
|
|
75
|
-
this.linkPreview = config.linkPreview ?? true;
|
|
76
|
-
this.textChunkLimit = config.textChunkLimit ?? 4000;
|
|
77
|
-
this.requireMention = config.requireMention ?? false;
|
|
78
|
-
if (config.botUsername) this.botUsername = config.botUsername.replace('@', '').toLowerCase();
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
setStreamHandler(handler: (msg: Message) => AsyncIterable<string>): void {
|
|
82
|
-
this.streamHandler = handler;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
async start(): Promise<void> {
|
|
86
|
-
if (!this.token) {
|
|
87
|
-
console.warn('[TelegramChannel] No bot token provided. Set TELEGRAM_BOT_TOKEN or pass token in config.');
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// Fetch bot info for username detection
|
|
92
|
-
try {
|
|
93
|
-
const me = await this.apiCall('getMe');
|
|
94
|
-
if (me?.result) {
|
|
95
|
-
this.botInfo = me.result;
|
|
96
|
-
this.botUsername = (me.result.username ?? '').toLowerCase();
|
|
97
|
-
console.log(`[TelegramChannel] Bot: @${this.botUsername}`);
|
|
98
|
-
}
|
|
99
|
-
} catch {}
|
|
100
|
-
|
|
101
|
-
if (this.mode === 'webhook') {
|
|
102
|
-
await this.startWebhook();
|
|
103
|
-
} else {
|
|
104
|
-
await this.startPolling();
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
async stop(): Promise<void> {
|
|
109
|
-
if (this.mode === 'webhook') {
|
|
110
|
-
await this.stopWebhook();
|
|
111
|
-
} else {
|
|
112
|
-
this.polling = false;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// ─── Polling Mode ────────────────────────────────────────
|
|
117
|
-
|
|
118
|
-
private async startPolling(): Promise<void> {
|
|
119
|
-
await this.apiCall('deleteWebhook');
|
|
120
|
-
console.log(`[TelegramChannel] Started long-polling mode`);
|
|
121
|
-
this.polling = true;
|
|
122
|
-
this.poll();
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
private async poll(): Promise<void> {
|
|
126
|
-
while (this.polling) {
|
|
127
|
-
try {
|
|
128
|
-
const updates = await this.getUpdates();
|
|
129
|
-
for (const update of updates) {
|
|
130
|
-
// Don't await — process concurrently for better responsiveness
|
|
131
|
-
this.processUpdate(update).catch((err) => {
|
|
132
|
-
console.error('[TelegramChannel] Update processing error:', err);
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
} catch (err) {
|
|
136
|
-
console.error('[TelegramChannel] Polling error:', err);
|
|
137
|
-
if (this.polling) {
|
|
138
|
-
await new Promise((r) => setTimeout(r, 5000));
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
private async getUpdates(): Promise<any[]> {
|
|
145
|
-
const url = `https://api.telegram.org/bot${this.token}/getUpdates?offset=${this.offset}&timeout=30&allowed_updates=${encodeURIComponent('["message","callback_query","message_reaction"]')}`;
|
|
146
|
-
const controller = new AbortController();
|
|
147
|
-
const timeout = setTimeout(() => controller.abort(), 40000);
|
|
148
|
-
|
|
149
|
-
try {
|
|
150
|
-
const res = await fetch(url, { signal: controller.signal });
|
|
151
|
-
const data = (await res.json()) as { ok: boolean; result: any[] };
|
|
152
|
-
if (data.ok && data.result.length > 0) {
|
|
153
|
-
this.offset = data.result[data.result.length - 1].update_id + 1;
|
|
154
|
-
}
|
|
155
|
-
return data.result || [];
|
|
156
|
-
} finally {
|
|
157
|
-
clearTimeout(timeout);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// ─── Webhook Mode ────────────────────────────────────────
|
|
162
|
-
|
|
163
|
-
private async startWebhook(): Promise<void> {
|
|
164
|
-
if (this.webhookUrl) {
|
|
165
|
-
const params: Record<string, unknown> = {
|
|
166
|
-
url: `${this.webhookUrl}/webhook/${this.token}`,
|
|
167
|
-
allowed_updates: ['message', 'callback_query', 'message_reaction'],
|
|
168
|
-
};
|
|
169
|
-
if (this.webhookSecret) params.secret_token = this.webhookSecret;
|
|
170
|
-
await this.apiCall('setWebhook', params);
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const express = (await import('express')).default;
|
|
174
|
-
const app = express();
|
|
175
|
-
app.use(express.json());
|
|
176
|
-
|
|
177
|
-
app.post(`/webhook/${this.token}`, async (req, res) => {
|
|
178
|
-
// Verify secret if configured
|
|
179
|
-
if (this.webhookSecret && req.headers['x-telegram-bot-api-secret-token'] !== this.webhookSecret) {
|
|
180
|
-
res.status(403).json({ error: 'Forbidden' });
|
|
181
|
-
return;
|
|
182
|
-
}
|
|
183
|
-
try {
|
|
184
|
-
// Don't await — respond quickly, process in background
|
|
185
|
-
this.processUpdate(req.body).catch((err) => {
|
|
186
|
-
console.error('[TelegramChannel] Webhook processing error:', err);
|
|
187
|
-
});
|
|
188
|
-
res.json({ ok: true });
|
|
189
|
-
} catch (err) {
|
|
190
|
-
console.error('[TelegramChannel] Webhook error:', err);
|
|
191
|
-
res.status(500).json({ error: 'Internal error' });
|
|
192
|
-
}
|
|
193
|
-
});
|
|
194
|
-
|
|
195
|
-
app.get('/health', (_req, res) => {
|
|
196
|
-
res.json({ status: 'ok', channel: 'telegram', mode: 'webhook', bot: this.botUsername });
|
|
197
|
-
});
|
|
198
|
-
|
|
199
|
-
return new Promise((resolve) => {
|
|
200
|
-
this.server = app.listen(this.port, () => {
|
|
201
|
-
console.log(`[TelegramChannel] Webhook server on port ${this.port}`);
|
|
202
|
-
resolve();
|
|
203
|
-
});
|
|
204
|
-
});
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
private async stopWebhook(): Promise<void> {
|
|
208
|
-
return new Promise((resolve, reject) => {
|
|
209
|
-
if (!this.server) return resolve();
|
|
210
|
-
this.server.close((err) => (err ? reject(err) : resolve()));
|
|
211
|
-
});
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
// ─── Update Processing ──────────────────────────────────
|
|
215
|
-
|
|
216
|
-
private async processUpdate(update: any): Promise<void> {
|
|
217
|
-
// Handle callback queries (inline buttons)
|
|
218
|
-
if (update.callback_query) {
|
|
219
|
-
await this.handleCallbackQuery(update.callback_query);
|
|
220
|
-
return;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
const message = update.message || update.edited_message;
|
|
224
|
-
if (!message || !this.handler) return;
|
|
225
|
-
|
|
226
|
-
// Handle commands
|
|
227
|
-
if (message.text?.startsWith('/')) {
|
|
228
|
-
const handled = await this.handleCommand(message);
|
|
229
|
-
if (handled) return;
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
// Extract text from various message types
|
|
233
|
-
const text = message.text || message.caption;
|
|
234
|
-
if (!text) return;
|
|
235
|
-
|
|
236
|
-
// Group mention filtering
|
|
237
|
-
if (this.isGroupChat(message) && this.requireMention) {
|
|
238
|
-
if (!this.isMentioned(text)) return;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
// Build message object
|
|
242
|
-
const msg: Message = {
|
|
243
|
-
id: `tg_${message.message_id}`,
|
|
244
|
-
role: 'user',
|
|
245
|
-
content: text,
|
|
246
|
-
timestamp: message.date * 1000,
|
|
247
|
-
metadata: {
|
|
248
|
-
sessionId: this.getSessionId(message),
|
|
249
|
-
chatId: message.chat.id,
|
|
250
|
-
userId: message.from?.id,
|
|
251
|
-
username: message.from?.username,
|
|
252
|
-
firstName: message.from?.first_name,
|
|
253
|
-
lastName: message.from?.last_name,
|
|
254
|
-
platform: 'telegram',
|
|
255
|
-
chatType: message.chat.type,
|
|
256
|
-
messageThreadId: message.message_thread_id,
|
|
257
|
-
replyToMessageId: message.message_id,
|
|
258
|
-
},
|
|
259
|
-
};
|
|
260
|
-
|
|
261
|
-
// Ack reaction — immediate visual feedback
|
|
262
|
-
if (this.ackReaction) {
|
|
263
|
-
this.setReaction(message.chat.id, message.message_id, this.ackReaction).catch(() => {});
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
// Typing indicator
|
|
267
|
-
const threadId = message.message_thread_id;
|
|
268
|
-
await this.sendTyping(message.chat.id, threadId);
|
|
269
|
-
const typingInterval = setInterval(() => {
|
|
270
|
-
this.sendTyping(message.chat.id, threadId).catch(() => {});
|
|
271
|
-
}, 4000);
|
|
272
|
-
|
|
273
|
-
try {
|
|
274
|
-
if (this.streamingEnabled && this.streamHandler) {
|
|
275
|
-
await this.streamResponse(message.chat.id, msg, message.message_id, threadId);
|
|
276
|
-
} else {
|
|
277
|
-
const response = await this.handler(msg);
|
|
278
|
-
await this.sendFormattedMessage(message.chat.id, response.content, message.message_id, threadId);
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
// Remove ack reaction after successful response
|
|
282
|
-
if (this.ackReaction) {
|
|
283
|
-
this.setReaction(message.chat.id, message.message_id, '').catch(() => {});
|
|
284
|
-
}
|
|
285
|
-
} catch (err) {
|
|
286
|
-
console.error('[TelegramChannel] Error processing message:', err);
|
|
287
|
-
await this.sendFormattedMessage(message.chat.id, '⚠️ Sorry, something went wrong. Please try again.', message.message_id, threadId);
|
|
288
|
-
} finally {
|
|
289
|
-
clearInterval(typingInterval);
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
// ─── Commands ───────────────────────────────────────────
|
|
294
|
-
|
|
295
|
-
private async handleCommand(message: any): Promise<boolean> {
|
|
296
|
-
const text = message.text ?? '';
|
|
297
|
-
const command = text.split(' ')[0].split('@')[0].toLowerCase(); // Strip @botname
|
|
298
|
-
|
|
299
|
-
switch (command) {
|
|
300
|
-
case '/start':
|
|
301
|
-
await this.sendFormattedMessage(
|
|
302
|
-
message.chat.id,
|
|
303
|
-
`👋 <b>Hello${message.from?.first_name ? ' ' + this.escapeHtml(message.from.first_name) : ''}!</b>\n\nI'm ready to help. Send me a message to get started.\n\nCommands:\n/help — Show available commands\n/status — Check bot status`,
|
|
304
|
-
undefined,
|
|
305
|
-
message.message_thread_id
|
|
306
|
-
);
|
|
307
|
-
return true;
|
|
308
|
-
|
|
309
|
-
case '/help':
|
|
310
|
-
await this.sendFormattedMessage(
|
|
311
|
-
message.chat.id,
|
|
312
|
-
`📖 <b>Available Commands</b>\n\n/start — Start conversation\n/help — Show this help\n/status — Bot status\n\nJust send a message and I'll respond!`,
|
|
313
|
-
undefined,
|
|
314
|
-
message.message_thread_id
|
|
315
|
-
);
|
|
316
|
-
return true;
|
|
317
|
-
|
|
318
|
-
case '/status':
|
|
319
|
-
const uptime = process.uptime();
|
|
320
|
-
const hours = Math.floor(uptime / 3600);
|
|
321
|
-
const mins = Math.floor((uptime % 3600) / 60);
|
|
322
|
-
await this.sendFormattedMessage(
|
|
323
|
-
message.chat.id,
|
|
324
|
-
`🟢 <b>Bot Status</b>\n\n⏱ Uptime: ${hours}h ${mins}m\n🤖 Bot: @${this.botUsername}\n💬 Mode: ${this.mode}\n📡 Streaming: ${this.streamingEnabled ? 'on' : 'off'}`,
|
|
325
|
-
undefined,
|
|
326
|
-
message.message_thread_id
|
|
327
|
-
);
|
|
328
|
-
return true;
|
|
329
|
-
|
|
330
|
-
default:
|
|
331
|
-
return false; // Not a recognized command, let it flow through as normal message
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
// ─── Callback Queries (Inline Buttons) ──────────────────
|
|
336
|
-
|
|
337
|
-
private async handleCallbackQuery(query: any): Promise<void> {
|
|
338
|
-
// Answer the callback to remove loading state
|
|
339
|
-
await this.apiCall('answerCallbackQuery', { callback_query_id: query.id });
|
|
340
|
-
|
|
341
|
-
if (!this.handler || !query.data) return;
|
|
342
|
-
|
|
343
|
-
const msg: Message = {
|
|
344
|
-
id: `tg_cb_${query.id}`,
|
|
345
|
-
role: 'user',
|
|
346
|
-
content: `callback_data: ${query.data}`,
|
|
347
|
-
timestamp: Date.now(),
|
|
348
|
-
metadata: {
|
|
349
|
-
sessionId: `tg_${query.message?.chat?.id ?? query.from.id}`,
|
|
350
|
-
chatId: query.message?.chat?.id ?? query.from.id,
|
|
351
|
-
userId: query.from.id,
|
|
352
|
-
username: query.from.username,
|
|
353
|
-
firstName: query.from.first_name,
|
|
354
|
-
platform: 'telegram',
|
|
355
|
-
chatType: query.message?.chat?.type ?? 'private',
|
|
356
|
-
isCallback: true,
|
|
357
|
-
},
|
|
358
|
-
};
|
|
359
|
-
|
|
360
|
-
try {
|
|
361
|
-
const response = await this.handler(msg);
|
|
362
|
-
const chatId = query.message?.chat?.id ?? query.from.id;
|
|
363
|
-
await this.sendFormattedMessage(chatId, response.content);
|
|
364
|
-
} catch (err) {
|
|
365
|
-
console.error('[TelegramChannel] Callback query error:', err);
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
// ─── Streaming ──────────────────────────────────────────
|
|
370
|
-
|
|
371
|
-
private async streamResponse(chatId: number | string, msg: Message, replyTo?: number, threadId?: number): Promise<void> {
|
|
372
|
-
if (!this.streamHandler) return;
|
|
373
|
-
|
|
374
|
-
let sentMessageId: number | null = null;
|
|
375
|
-
let fullText = '';
|
|
376
|
-
let lastEditTime = 0;
|
|
377
|
-
const EDIT_INTERVAL = 800; // Edit slightly faster than before
|
|
378
|
-
const MIN_FIRST_SEND = 20; // Min chars before first send (avoid tiny initial message)
|
|
379
|
-
|
|
380
|
-
const doEdit = async (final: boolean = false) => {
|
|
381
|
-
if (!sentMessageId || !fullText) return;
|
|
382
|
-
const displayText = final ? fullText : fullText + ' ▍'; // Cursor indicator while streaming
|
|
383
|
-
try {
|
|
384
|
-
await this.apiCall('editMessageText', {
|
|
385
|
-
chat_id: chatId,
|
|
386
|
-
message_id: sentMessageId,
|
|
387
|
-
text: displayText,
|
|
388
|
-
parse_mode: 'HTML',
|
|
389
|
-
disable_web_page_preview: !this.linkPreview,
|
|
390
|
-
});
|
|
391
|
-
lastEditTime = Date.now();
|
|
392
|
-
} catch {
|
|
393
|
-
// HTML parse failed, try plain text
|
|
394
|
-
try {
|
|
395
|
-
await this.apiCall('editMessageText', {
|
|
396
|
-
chat_id: chatId,
|
|
397
|
-
message_id: sentMessageId,
|
|
398
|
-
text: displayText,
|
|
399
|
-
});
|
|
400
|
-
lastEditTime = Date.now();
|
|
401
|
-
} catch {}
|
|
402
|
-
}
|
|
403
|
-
};
|
|
404
|
-
|
|
405
|
-
try {
|
|
406
|
-
for await (const chunk of this.streamHandler(msg)) {
|
|
407
|
-
fullText += chunk;
|
|
408
|
-
|
|
409
|
-
if (!sentMessageId && fullText.length >= MIN_FIRST_SEND) {
|
|
410
|
-
const result = await this.sendFormattedMessage(chatId, fullText + ' ▍', replyTo, threadId);
|
|
411
|
-
sentMessageId = result?.message_id;
|
|
412
|
-
lastEditTime = Date.now();
|
|
413
|
-
} else if (sentMessageId) {
|
|
414
|
-
const now = Date.now();
|
|
415
|
-
if (now - lastEditTime >= EDIT_INTERVAL) {
|
|
416
|
-
await doEdit();
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
// Final edit — remove cursor, clean formatting
|
|
422
|
-
if (sentMessageId && fullText) {
|
|
423
|
-
await doEdit(true);
|
|
424
|
-
} else if (!sentMessageId && fullText) {
|
|
425
|
-
// Never sent first message (very short response)
|
|
426
|
-
await this.sendFormattedMessage(chatId, fullText, replyTo, threadId);
|
|
427
|
-
}
|
|
428
|
-
} catch (err) {
|
|
429
|
-
if (!sentMessageId && fullText) {
|
|
430
|
-
await this.sendFormattedMessage(chatId, fullText, replyTo, threadId);
|
|
431
|
-
}
|
|
432
|
-
throw err;
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
// ─── Message Sending ───────────────────────────────────
|
|
437
|
-
|
|
438
|
-
async sendFormattedMessage(chatId: number | string, text: string, replyTo?: number, threadId?: number): Promise<any> {
|
|
439
|
-
const chunks = this.smartSplit(text, this.textChunkLimit);
|
|
440
|
-
let lastResult: any = null;
|
|
441
|
-
|
|
442
|
-
for (const chunk of chunks) {
|
|
443
|
-
const baseParams: Record<string, unknown> = {
|
|
444
|
-
chat_id: chatId,
|
|
445
|
-
disable_web_page_preview: !this.linkPreview,
|
|
446
|
-
...(replyTo ? { reply_to_message_id: replyTo } : {}),
|
|
447
|
-
...(threadId ? { message_thread_id: threadId } : {}),
|
|
448
|
-
};
|
|
449
|
-
|
|
450
|
-
// Try HTML first (richer formatting)
|
|
451
|
-
try {
|
|
452
|
-
const htmlText = this.markdownToHtml(chunk);
|
|
453
|
-
lastResult = await this.apiCall('sendMessage', {
|
|
454
|
-
...baseParams,
|
|
455
|
-
text: htmlText,
|
|
456
|
-
parse_mode: 'HTML',
|
|
457
|
-
});
|
|
458
|
-
} catch {
|
|
459
|
-
// HTML failed, try Markdown
|
|
460
|
-
try {
|
|
461
|
-
lastResult = await this.apiCall('sendMessage', {
|
|
462
|
-
...baseParams,
|
|
463
|
-
text: chunk,
|
|
464
|
-
parse_mode: 'Markdown',
|
|
465
|
-
});
|
|
466
|
-
} catch {
|
|
467
|
-
// All parsing failed, send plain text
|
|
468
|
-
lastResult = await this.apiCall('sendMessage', {
|
|
469
|
-
...baseParams,
|
|
470
|
-
text: chunk,
|
|
471
|
-
});
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
// Only reply to first chunk
|
|
476
|
-
replyTo = undefined;
|
|
477
|
-
}
|
|
478
|
-
return lastResult?.result;
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
async sendMessage(chatId: number | string, text: string): Promise<void> {
|
|
482
|
-
await this.sendFormattedMessage(chatId, text);
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
// ─── Reactions ──────────────────────────────────────────
|
|
486
|
-
|
|
487
|
-
private async setReaction(chatId: number | string, messageId: number, emoji: string): Promise<void> {
|
|
488
|
-
try {
|
|
489
|
-
await this.apiCall('setMessageReaction', {
|
|
490
|
-
chat_id: chatId,
|
|
491
|
-
message_id: messageId,
|
|
492
|
-
reaction: emoji ? [{ type: 'emoji', emoji }] : [],
|
|
493
|
-
});
|
|
494
|
-
} catch {
|
|
495
|
-
// Reactions may not be available in all chats
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
// ─── Typing ─────────────────────────────────────────────
|
|
500
|
-
|
|
501
|
-
private async sendTyping(chatId: number | string, threadId?: number): Promise<void> {
|
|
502
|
-
await this.apiCall('sendChatAction', {
|
|
503
|
-
chat_id: chatId,
|
|
504
|
-
action: 'typing',
|
|
505
|
-
...(threadId ? { message_thread_id: threadId } : {}),
|
|
506
|
-
}).catch(() => {});
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
// ─── Helpers ────────────────────────────────────────────
|
|
510
|
-
|
|
511
|
-
private isGroupChat(message: any): boolean {
|
|
512
|
-
return message.chat.type === 'group' || message.chat.type === 'supergroup';
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
private isMentioned(text: string): boolean {
|
|
516
|
-
if (!this.botUsername) return true;
|
|
517
|
-
const lower = text.toLowerCase();
|
|
518
|
-
return lower.includes(`@${this.botUsername}`);
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
private getSessionId(message: any): string {
|
|
522
|
-
const chatId = message.chat.id;
|
|
523
|
-
const threadId = message.message_thread_id;
|
|
524
|
-
if (threadId && message.chat.is_forum) {
|
|
525
|
-
return `tg_${chatId}_topic_${threadId}`;
|
|
526
|
-
}
|
|
527
|
-
return `tg_${chatId}`;
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
private escapeHtml(text: string): string {
|
|
531
|
-
return text
|
|
532
|
-
.replace(/&/g, '&')
|
|
533
|
-
.replace(/</g, '<')
|
|
534
|
-
.replace(/>/g, '>')
|
|
535
|
-
.replace(/"/g, '"');
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
/**
|
|
539
|
-
* Convert basic Markdown to Telegram-safe HTML.
|
|
540
|
-
* Handles: bold, italic, code, code blocks, links.
|
|
541
|
-
*/
|
|
542
|
-
private markdownToHtml(text: string): string {
|
|
543
|
-
let html = this.escapeHtml(text);
|
|
544
|
-
|
|
545
|
-
// Code blocks (```...```)
|
|
546
|
-
html = html.replace(/```(\w*)\n?([\s\S]*?)```/g, (_m, lang, code) => {
|
|
547
|
-
return `<pre${lang ? ` class="language-${lang}"` : ''}>${code}</pre>`;
|
|
548
|
-
});
|
|
549
|
-
|
|
550
|
-
// Inline code (`...`)
|
|
551
|
-
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
|
|
552
|
-
|
|
553
|
-
// Bold (**...**)
|
|
554
|
-
html = html.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>');
|
|
555
|
-
|
|
556
|
-
// Italic (*...*)
|
|
557
|
-
html = html.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, '<i>$1</i>');
|
|
558
|
-
|
|
559
|
-
// Links [text](url)
|
|
560
|
-
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
|
|
561
|
-
|
|
562
|
-
return html;
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
/**
|
|
566
|
-
* Smart text splitting — prefer paragraph boundaries (blank lines) before hard length split.
|
|
567
|
-
* Aligned with OpenClaw's chunkMode="newline" behavior.
|
|
568
|
-
*/
|
|
569
|
-
private smartSplit(text: string, maxLen: number): string[] {
|
|
570
|
-
if (text.length <= maxLen) return [text];
|
|
571
|
-
|
|
572
|
-
const parts: string[] = [];
|
|
573
|
-
let remaining = text;
|
|
574
|
-
|
|
575
|
-
while (remaining.length > maxLen) {
|
|
576
|
-
// Try to find a paragraph break (double newline) near the limit
|
|
577
|
-
let splitAt = remaining.lastIndexOf('\n\n', maxLen);
|
|
578
|
-
if (splitAt < maxLen * 0.3) {
|
|
579
|
-
// No good paragraph break, try single newline
|
|
580
|
-
splitAt = remaining.lastIndexOf('\n', maxLen);
|
|
581
|
-
}
|
|
582
|
-
if (splitAt < maxLen * 0.3) {
|
|
583
|
-
// No good newline, hard split at limit
|
|
584
|
-
splitAt = maxLen;
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
parts.push(remaining.slice(0, splitAt).trimEnd());
|
|
588
|
-
remaining = remaining.slice(splitAt).trimStart();
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
if (remaining) parts.push(remaining);
|
|
592
|
-
return parts;
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
private async apiCall(method: string, body?: Record<string, unknown>): Promise<any> {
|
|
596
|
-
const url = `https://api.telegram.org/bot${this.token}/${method}`;
|
|
597
|
-
try {
|
|
598
|
-
const res = await fetch(url, {
|
|
599
|
-
method: 'POST',
|
|
600
|
-
headers: { 'Content-Type': 'application/json' },
|
|
601
|
-
body: body ? JSON.stringify(body) : undefined,
|
|
602
|
-
});
|
|
603
|
-
const data = await res.json() as { ok: boolean; result?: any; description?: string };
|
|
604
|
-
if (!data.ok) {
|
|
605
|
-
const err = new Error(`Telegram API ${method} failed: ${data.description}`);
|
|
606
|
-
(err as any).telegramError = data;
|
|
607
|
-
throw err;
|
|
608
|
-
}
|
|
609
|
-
return data;
|
|
610
|
-
} catch (err) {
|
|
611
|
-
if ((err as any).telegramError) throw err;
|
|
612
|
-
console.error(`[TelegramChannel] API call ${method} failed:`, err);
|
|
613
|
-
throw err;
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
}
|
|
1
|
+
import type { Message } from '../core/types';
|
|
2
|
+
import { BaseChannel } from './index';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Telegram channel — production-quality Telegram bot integration.
|
|
6
|
+
*
|
|
7
|
+
* Features (aligned with OpenClaw):
|
|
8
|
+
* - Live stream preview (sendMessage + editMessageText)
|
|
9
|
+
* - Ack reaction on message receipt
|
|
10
|
+
* - Typing indicator throughout processing
|
|
11
|
+
* - HTML parse mode with Markdown fallback
|
|
12
|
+
* - Smart text chunking (paragraph-aware)
|
|
13
|
+
* - /start, /help, /status commands
|
|
14
|
+
* - Photo/document caption handling
|
|
15
|
+
* - Callback query (inline button) support
|
|
16
|
+
* - Reply threading
|
|
17
|
+
* - Error recovery with plain-text fallback
|
|
18
|
+
* - Forum topic support
|
|
19
|
+
* - Group mention filtering
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export interface TelegramChannelConfig {
|
|
23
|
+
token?: string;
|
|
24
|
+
mode?: 'polling' | 'webhook';
|
|
25
|
+
webhookUrl?: string;
|
|
26
|
+
webhookSecret?: string;
|
|
27
|
+
port?: number;
|
|
28
|
+
// Feature flags
|
|
29
|
+
streaming?: boolean | 'off' | 'partial';
|
|
30
|
+
ackReaction?: string; // emoji to react with on receipt, e.g. "👀"
|
|
31
|
+
linkPreview?: boolean;
|
|
32
|
+
textChunkLimit?: number;
|
|
33
|
+
requireMention?: boolean; // for groups
|
|
34
|
+
botUsername?: string; // for mention detection
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class TelegramChannel extends BaseChannel {
|
|
38
|
+
readonly type = 'telegram';
|
|
39
|
+
private token: string;
|
|
40
|
+
private mode: 'polling' | 'webhook';
|
|
41
|
+
private webhookUrl?: string;
|
|
42
|
+
private webhookSecret?: string;
|
|
43
|
+
private port: number;
|
|
44
|
+
private botUsername: string = '';
|
|
45
|
+
private botInfo: any = null;
|
|
46
|
+
|
|
47
|
+
// Config
|
|
48
|
+
private streamingEnabled: boolean;
|
|
49
|
+
private ackReaction: string;
|
|
50
|
+
private linkPreview: boolean;
|
|
51
|
+
private textChunkLimit: number;
|
|
52
|
+
private requireMention: boolean;
|
|
53
|
+
|
|
54
|
+
// Polling state
|
|
55
|
+
private offset: number = 0;
|
|
56
|
+
private polling: boolean = false;
|
|
57
|
+
|
|
58
|
+
// Webhook state
|
|
59
|
+
private server: import('http').Server | null = null;
|
|
60
|
+
|
|
61
|
+
// Stream handler — set by runtime when provider supports streaming
|
|
62
|
+
private streamHandler?: (msg: Message) => AsyncIterable<string>;
|
|
63
|
+
|
|
64
|
+
constructor(config: TelegramChannelConfig = {}) {
|
|
65
|
+
super();
|
|
66
|
+
this.token = config.token ?? process.env.TELEGRAM_BOT_TOKEN ?? '';
|
|
67
|
+
this.mode = config.mode ?? 'polling';
|
|
68
|
+
this.webhookUrl = config.webhookUrl;
|
|
69
|
+
this.webhookSecret = config.webhookSecret;
|
|
70
|
+
this.port = config.port ?? 3001;
|
|
71
|
+
|
|
72
|
+
// Feature config
|
|
73
|
+
this.streamingEnabled = config.streaming !== false && config.streaming !== 'off';
|
|
74
|
+
this.ackReaction = config.ackReaction ?? '👀';
|
|
75
|
+
this.linkPreview = config.linkPreview ?? true;
|
|
76
|
+
this.textChunkLimit = config.textChunkLimit ?? 4000;
|
|
77
|
+
this.requireMention = config.requireMention ?? false;
|
|
78
|
+
if (config.botUsername) this.botUsername = config.botUsername.replace('@', '').toLowerCase();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
setStreamHandler(handler: (msg: Message) => AsyncIterable<string>): void {
|
|
82
|
+
this.streamHandler = handler;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async start(): Promise<void> {
|
|
86
|
+
if (!this.token) {
|
|
87
|
+
console.warn('[TelegramChannel] No bot token provided. Set TELEGRAM_BOT_TOKEN or pass token in config.');
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Fetch bot info for username detection
|
|
92
|
+
try {
|
|
93
|
+
const me = await this.apiCall('getMe');
|
|
94
|
+
if (me?.result) {
|
|
95
|
+
this.botInfo = me.result;
|
|
96
|
+
this.botUsername = (me.result.username ?? '').toLowerCase();
|
|
97
|
+
console.log(`[TelegramChannel] Bot: @${this.botUsername}`);
|
|
98
|
+
}
|
|
99
|
+
} catch {}
|
|
100
|
+
|
|
101
|
+
if (this.mode === 'webhook') {
|
|
102
|
+
await this.startWebhook();
|
|
103
|
+
} else {
|
|
104
|
+
await this.startPolling();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async stop(): Promise<void> {
|
|
109
|
+
if (this.mode === 'webhook') {
|
|
110
|
+
await this.stopWebhook();
|
|
111
|
+
} else {
|
|
112
|
+
this.polling = false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ─── Polling Mode ────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
private async startPolling(): Promise<void> {
|
|
119
|
+
await this.apiCall('deleteWebhook');
|
|
120
|
+
console.log(`[TelegramChannel] Started long-polling mode`);
|
|
121
|
+
this.polling = true;
|
|
122
|
+
this.poll();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private async poll(): Promise<void> {
|
|
126
|
+
while (this.polling) {
|
|
127
|
+
try {
|
|
128
|
+
const updates = await this.getUpdates();
|
|
129
|
+
for (const update of updates) {
|
|
130
|
+
// Don't await — process concurrently for better responsiveness
|
|
131
|
+
this.processUpdate(update).catch((err) => {
|
|
132
|
+
console.error('[TelegramChannel] Update processing error:', err);
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
} catch (err) {
|
|
136
|
+
console.error('[TelegramChannel] Polling error:', err);
|
|
137
|
+
if (this.polling) {
|
|
138
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private async getUpdates(): Promise<any[]> {
|
|
145
|
+
const url = `https://api.telegram.org/bot${this.token}/getUpdates?offset=${this.offset}&timeout=30&allowed_updates=${encodeURIComponent('["message","callback_query","message_reaction"]')}`;
|
|
146
|
+
const controller = new AbortController();
|
|
147
|
+
const timeout = setTimeout(() => controller.abort(), 40000);
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
const res = await fetch(url, { signal: controller.signal });
|
|
151
|
+
const data = (await res.json()) as { ok: boolean; result: any[] };
|
|
152
|
+
if (data.ok && data.result.length > 0) {
|
|
153
|
+
this.offset = data.result[data.result.length - 1].update_id + 1;
|
|
154
|
+
}
|
|
155
|
+
return data.result || [];
|
|
156
|
+
} finally {
|
|
157
|
+
clearTimeout(timeout);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ─── Webhook Mode ────────────────────────────────────────
|
|
162
|
+
|
|
163
|
+
private async startWebhook(): Promise<void> {
|
|
164
|
+
if (this.webhookUrl) {
|
|
165
|
+
const params: Record<string, unknown> = {
|
|
166
|
+
url: `${this.webhookUrl}/webhook/${this.token}`,
|
|
167
|
+
allowed_updates: ['message', 'callback_query', 'message_reaction'],
|
|
168
|
+
};
|
|
169
|
+
if (this.webhookSecret) params.secret_token = this.webhookSecret;
|
|
170
|
+
await this.apiCall('setWebhook', params);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const express = (await import('express')).default;
|
|
174
|
+
const app = express();
|
|
175
|
+
app.use(express.json());
|
|
176
|
+
|
|
177
|
+
app.post(`/webhook/${this.token}`, async (req, res) => {
|
|
178
|
+
// Verify secret if configured
|
|
179
|
+
if (this.webhookSecret && req.headers['x-telegram-bot-api-secret-token'] !== this.webhookSecret) {
|
|
180
|
+
res.status(403).json({ error: 'Forbidden' });
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
// Don't await — respond quickly, process in background
|
|
185
|
+
this.processUpdate(req.body).catch((err) => {
|
|
186
|
+
console.error('[TelegramChannel] Webhook processing error:', err);
|
|
187
|
+
});
|
|
188
|
+
res.json({ ok: true });
|
|
189
|
+
} catch (err) {
|
|
190
|
+
console.error('[TelegramChannel] Webhook error:', err);
|
|
191
|
+
res.status(500).json({ error: 'Internal error' });
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
app.get('/health', (_req, res) => {
|
|
196
|
+
res.json({ status: 'ok', channel: 'telegram', mode: 'webhook', bot: this.botUsername });
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
return new Promise((resolve) => {
|
|
200
|
+
this.server = app.listen(this.port, () => {
|
|
201
|
+
console.log(`[TelegramChannel] Webhook server on port ${this.port}`);
|
|
202
|
+
resolve();
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private async stopWebhook(): Promise<void> {
|
|
208
|
+
return new Promise((resolve, reject) => {
|
|
209
|
+
if (!this.server) return resolve();
|
|
210
|
+
this.server.close((err) => (err ? reject(err) : resolve()));
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ─── Update Processing ──────────────────────────────────
|
|
215
|
+
|
|
216
|
+
private async processUpdate(update: any): Promise<void> {
|
|
217
|
+
// Handle callback queries (inline buttons)
|
|
218
|
+
if (update.callback_query) {
|
|
219
|
+
await this.handleCallbackQuery(update.callback_query);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const message = update.message || update.edited_message;
|
|
224
|
+
if (!message || !this.handler) return;
|
|
225
|
+
|
|
226
|
+
// Handle commands
|
|
227
|
+
if (message.text?.startsWith('/')) {
|
|
228
|
+
const handled = await this.handleCommand(message);
|
|
229
|
+
if (handled) return;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Extract text from various message types
|
|
233
|
+
const text = message.text || message.caption;
|
|
234
|
+
if (!text) return;
|
|
235
|
+
|
|
236
|
+
// Group mention filtering
|
|
237
|
+
if (this.isGroupChat(message) && this.requireMention) {
|
|
238
|
+
if (!this.isMentioned(text)) return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Build message object
|
|
242
|
+
const msg: Message = {
|
|
243
|
+
id: `tg_${message.message_id}`,
|
|
244
|
+
role: 'user',
|
|
245
|
+
content: text,
|
|
246
|
+
timestamp: message.date * 1000,
|
|
247
|
+
metadata: {
|
|
248
|
+
sessionId: this.getSessionId(message),
|
|
249
|
+
chatId: message.chat.id,
|
|
250
|
+
userId: message.from?.id,
|
|
251
|
+
username: message.from?.username,
|
|
252
|
+
firstName: message.from?.first_name,
|
|
253
|
+
lastName: message.from?.last_name,
|
|
254
|
+
platform: 'telegram',
|
|
255
|
+
chatType: message.chat.type,
|
|
256
|
+
messageThreadId: message.message_thread_id,
|
|
257
|
+
replyToMessageId: message.message_id,
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// Ack reaction — immediate visual feedback
|
|
262
|
+
if (this.ackReaction) {
|
|
263
|
+
this.setReaction(message.chat.id, message.message_id, this.ackReaction).catch(() => {});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Typing indicator
|
|
267
|
+
const threadId = message.message_thread_id;
|
|
268
|
+
await this.sendTyping(message.chat.id, threadId);
|
|
269
|
+
const typingInterval = setInterval(() => {
|
|
270
|
+
this.sendTyping(message.chat.id, threadId).catch(() => {});
|
|
271
|
+
}, 4000);
|
|
272
|
+
|
|
273
|
+
try {
|
|
274
|
+
if (this.streamingEnabled && this.streamHandler) {
|
|
275
|
+
await this.streamResponse(message.chat.id, msg, message.message_id, threadId);
|
|
276
|
+
} else {
|
|
277
|
+
const response = await this.handler(msg);
|
|
278
|
+
await this.sendFormattedMessage(message.chat.id, response.content, message.message_id, threadId);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Remove ack reaction after successful response
|
|
282
|
+
if (this.ackReaction) {
|
|
283
|
+
this.setReaction(message.chat.id, message.message_id, '').catch(() => {});
|
|
284
|
+
}
|
|
285
|
+
} catch (err) {
|
|
286
|
+
console.error('[TelegramChannel] Error processing message:', err);
|
|
287
|
+
await this.sendFormattedMessage(message.chat.id, '⚠️ Sorry, something went wrong. Please try again.', message.message_id, threadId);
|
|
288
|
+
} finally {
|
|
289
|
+
clearInterval(typingInterval);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ─── Commands ───────────────────────────────────────────
|
|
294
|
+
|
|
295
|
+
private async handleCommand(message: any): Promise<boolean> {
|
|
296
|
+
const text = message.text ?? '';
|
|
297
|
+
const command = text.split(' ')[0].split('@')[0].toLowerCase(); // Strip @botname
|
|
298
|
+
|
|
299
|
+
switch (command) {
|
|
300
|
+
case '/start':
|
|
301
|
+
await this.sendFormattedMessage(
|
|
302
|
+
message.chat.id,
|
|
303
|
+
`👋 <b>Hello${message.from?.first_name ? ' ' + this.escapeHtml(message.from.first_name) : ''}!</b>\n\nI'm ready to help. Send me a message to get started.\n\nCommands:\n/help — Show available commands\n/status — Check bot status`,
|
|
304
|
+
undefined,
|
|
305
|
+
message.message_thread_id
|
|
306
|
+
);
|
|
307
|
+
return true;
|
|
308
|
+
|
|
309
|
+
case '/help':
|
|
310
|
+
await this.sendFormattedMessage(
|
|
311
|
+
message.chat.id,
|
|
312
|
+
`📖 <b>Available Commands</b>\n\n/start — Start conversation\n/help — Show this help\n/status — Bot status\n\nJust send a message and I'll respond!`,
|
|
313
|
+
undefined,
|
|
314
|
+
message.message_thread_id
|
|
315
|
+
);
|
|
316
|
+
return true;
|
|
317
|
+
|
|
318
|
+
case '/status':
|
|
319
|
+
const uptime = process.uptime();
|
|
320
|
+
const hours = Math.floor(uptime / 3600);
|
|
321
|
+
const mins = Math.floor((uptime % 3600) / 60);
|
|
322
|
+
await this.sendFormattedMessage(
|
|
323
|
+
message.chat.id,
|
|
324
|
+
`🟢 <b>Bot Status</b>\n\n⏱ Uptime: ${hours}h ${mins}m\n🤖 Bot: @${this.botUsername}\n💬 Mode: ${this.mode}\n📡 Streaming: ${this.streamingEnabled ? 'on' : 'off'}`,
|
|
325
|
+
undefined,
|
|
326
|
+
message.message_thread_id
|
|
327
|
+
);
|
|
328
|
+
return true;
|
|
329
|
+
|
|
330
|
+
default:
|
|
331
|
+
return false; // Not a recognized command, let it flow through as normal message
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ─── Callback Queries (Inline Buttons) ──────────────────
|
|
336
|
+
|
|
337
|
+
private async handleCallbackQuery(query: any): Promise<void> {
|
|
338
|
+
// Answer the callback to remove loading state
|
|
339
|
+
await this.apiCall('answerCallbackQuery', { callback_query_id: query.id });
|
|
340
|
+
|
|
341
|
+
if (!this.handler || !query.data) return;
|
|
342
|
+
|
|
343
|
+
const msg: Message = {
|
|
344
|
+
id: `tg_cb_${query.id}`,
|
|
345
|
+
role: 'user',
|
|
346
|
+
content: `callback_data: ${query.data}`,
|
|
347
|
+
timestamp: Date.now(),
|
|
348
|
+
metadata: {
|
|
349
|
+
sessionId: `tg_${query.message?.chat?.id ?? query.from.id}`,
|
|
350
|
+
chatId: query.message?.chat?.id ?? query.from.id,
|
|
351
|
+
userId: query.from.id,
|
|
352
|
+
username: query.from.username,
|
|
353
|
+
firstName: query.from.first_name,
|
|
354
|
+
platform: 'telegram',
|
|
355
|
+
chatType: query.message?.chat?.type ?? 'private',
|
|
356
|
+
isCallback: true,
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
try {
|
|
361
|
+
const response = await this.handler(msg);
|
|
362
|
+
const chatId = query.message?.chat?.id ?? query.from.id;
|
|
363
|
+
await this.sendFormattedMessage(chatId, response.content);
|
|
364
|
+
} catch (err) {
|
|
365
|
+
console.error('[TelegramChannel] Callback query error:', err);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ─── Streaming ──────────────────────────────────────────
|
|
370
|
+
|
|
371
|
+
private async streamResponse(chatId: number | string, msg: Message, replyTo?: number, threadId?: number): Promise<void> {
|
|
372
|
+
if (!this.streamHandler) return;
|
|
373
|
+
|
|
374
|
+
let sentMessageId: number | null = null;
|
|
375
|
+
let fullText = '';
|
|
376
|
+
let lastEditTime = 0;
|
|
377
|
+
const EDIT_INTERVAL = 800; // Edit slightly faster than before
|
|
378
|
+
const MIN_FIRST_SEND = 20; // Min chars before first send (avoid tiny initial message)
|
|
379
|
+
|
|
380
|
+
const doEdit = async (final: boolean = false) => {
|
|
381
|
+
if (!sentMessageId || !fullText) return;
|
|
382
|
+
const displayText = final ? fullText : fullText + ' ▍'; // Cursor indicator while streaming
|
|
383
|
+
try {
|
|
384
|
+
await this.apiCall('editMessageText', {
|
|
385
|
+
chat_id: chatId,
|
|
386
|
+
message_id: sentMessageId,
|
|
387
|
+
text: displayText,
|
|
388
|
+
parse_mode: 'HTML',
|
|
389
|
+
disable_web_page_preview: !this.linkPreview,
|
|
390
|
+
});
|
|
391
|
+
lastEditTime = Date.now();
|
|
392
|
+
} catch {
|
|
393
|
+
// HTML parse failed, try plain text
|
|
394
|
+
try {
|
|
395
|
+
await this.apiCall('editMessageText', {
|
|
396
|
+
chat_id: chatId,
|
|
397
|
+
message_id: sentMessageId,
|
|
398
|
+
text: displayText,
|
|
399
|
+
});
|
|
400
|
+
lastEditTime = Date.now();
|
|
401
|
+
} catch {}
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
try {
|
|
406
|
+
for await (const chunk of this.streamHandler(msg)) {
|
|
407
|
+
fullText += chunk;
|
|
408
|
+
|
|
409
|
+
if (!sentMessageId && fullText.length >= MIN_FIRST_SEND) {
|
|
410
|
+
const result = await this.sendFormattedMessage(chatId, fullText + ' ▍', replyTo, threadId);
|
|
411
|
+
sentMessageId = result?.message_id;
|
|
412
|
+
lastEditTime = Date.now();
|
|
413
|
+
} else if (sentMessageId) {
|
|
414
|
+
const now = Date.now();
|
|
415
|
+
if (now - lastEditTime >= EDIT_INTERVAL) {
|
|
416
|
+
await doEdit();
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Final edit — remove cursor, clean formatting
|
|
422
|
+
if (sentMessageId && fullText) {
|
|
423
|
+
await doEdit(true);
|
|
424
|
+
} else if (!sentMessageId && fullText) {
|
|
425
|
+
// Never sent first message (very short response)
|
|
426
|
+
await this.sendFormattedMessage(chatId, fullText, replyTo, threadId);
|
|
427
|
+
}
|
|
428
|
+
} catch (err) {
|
|
429
|
+
if (!sentMessageId && fullText) {
|
|
430
|
+
await this.sendFormattedMessage(chatId, fullText, replyTo, threadId);
|
|
431
|
+
}
|
|
432
|
+
throw err;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// ─── Message Sending ───────────────────────────────────
|
|
437
|
+
|
|
438
|
+
async sendFormattedMessage(chatId: number | string, text: string, replyTo?: number, threadId?: number): Promise<any> {
|
|
439
|
+
const chunks = this.smartSplit(text, this.textChunkLimit);
|
|
440
|
+
let lastResult: any = null;
|
|
441
|
+
|
|
442
|
+
for (const chunk of chunks) {
|
|
443
|
+
const baseParams: Record<string, unknown> = {
|
|
444
|
+
chat_id: chatId,
|
|
445
|
+
disable_web_page_preview: !this.linkPreview,
|
|
446
|
+
...(replyTo ? { reply_to_message_id: replyTo } : {}),
|
|
447
|
+
...(threadId ? { message_thread_id: threadId } : {}),
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
// Try HTML first (richer formatting)
|
|
451
|
+
try {
|
|
452
|
+
const htmlText = this.markdownToHtml(chunk);
|
|
453
|
+
lastResult = await this.apiCall('sendMessage', {
|
|
454
|
+
...baseParams,
|
|
455
|
+
text: htmlText,
|
|
456
|
+
parse_mode: 'HTML',
|
|
457
|
+
});
|
|
458
|
+
} catch {
|
|
459
|
+
// HTML failed, try Markdown
|
|
460
|
+
try {
|
|
461
|
+
lastResult = await this.apiCall('sendMessage', {
|
|
462
|
+
...baseParams,
|
|
463
|
+
text: chunk,
|
|
464
|
+
parse_mode: 'Markdown',
|
|
465
|
+
});
|
|
466
|
+
} catch {
|
|
467
|
+
// All parsing failed, send plain text
|
|
468
|
+
lastResult = await this.apiCall('sendMessage', {
|
|
469
|
+
...baseParams,
|
|
470
|
+
text: chunk,
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// Only reply to first chunk
|
|
476
|
+
replyTo = undefined;
|
|
477
|
+
}
|
|
478
|
+
return lastResult?.result;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
async sendMessage(chatId: number | string, text: string): Promise<void> {
|
|
482
|
+
await this.sendFormattedMessage(chatId, text);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// ─── Reactions ──────────────────────────────────────────
|
|
486
|
+
|
|
487
|
+
private async setReaction(chatId: number | string, messageId: number, emoji: string): Promise<void> {
|
|
488
|
+
try {
|
|
489
|
+
await this.apiCall('setMessageReaction', {
|
|
490
|
+
chat_id: chatId,
|
|
491
|
+
message_id: messageId,
|
|
492
|
+
reaction: emoji ? [{ type: 'emoji', emoji }] : [],
|
|
493
|
+
});
|
|
494
|
+
} catch {
|
|
495
|
+
// Reactions may not be available in all chats
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// ─── Typing ─────────────────────────────────────────────
|
|
500
|
+
|
|
501
|
+
private async sendTyping(chatId: number | string, threadId?: number): Promise<void> {
|
|
502
|
+
await this.apiCall('sendChatAction', {
|
|
503
|
+
chat_id: chatId,
|
|
504
|
+
action: 'typing',
|
|
505
|
+
...(threadId ? { message_thread_id: threadId } : {}),
|
|
506
|
+
}).catch(() => {});
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// ─── Helpers ────────────────────────────────────────────
|
|
510
|
+
|
|
511
|
+
private isGroupChat(message: any): boolean {
|
|
512
|
+
return message.chat.type === 'group' || message.chat.type === 'supergroup';
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
private isMentioned(text: string): boolean {
|
|
516
|
+
if (!this.botUsername) return true;
|
|
517
|
+
const lower = text.toLowerCase();
|
|
518
|
+
return lower.includes(`@${this.botUsername}`);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
private getSessionId(message: any): string {
|
|
522
|
+
const chatId = message.chat.id;
|
|
523
|
+
const threadId = message.message_thread_id;
|
|
524
|
+
if (threadId && message.chat.is_forum) {
|
|
525
|
+
return `tg_${chatId}_topic_${threadId}`;
|
|
526
|
+
}
|
|
527
|
+
return `tg_${chatId}`;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
private escapeHtml(text: string): string {
|
|
531
|
+
return text
|
|
532
|
+
.replace(/&/g, '&')
|
|
533
|
+
.replace(/</g, '<')
|
|
534
|
+
.replace(/>/g, '>')
|
|
535
|
+
.replace(/"/g, '"');
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Convert basic Markdown to Telegram-safe HTML.
|
|
540
|
+
* Handles: bold, italic, code, code blocks, links.
|
|
541
|
+
*/
|
|
542
|
+
private markdownToHtml(text: string): string {
|
|
543
|
+
let html = this.escapeHtml(text);
|
|
544
|
+
|
|
545
|
+
// Code blocks (```...```)
|
|
546
|
+
html = html.replace(/```(\w*)\n?([\s\S]*?)```/g, (_m, lang, code) => {
|
|
547
|
+
return `<pre${lang ? ` class="language-${lang}"` : ''}>${code}</pre>`;
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
// Inline code (`...`)
|
|
551
|
+
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
|
|
552
|
+
|
|
553
|
+
// Bold (**...**)
|
|
554
|
+
html = html.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>');
|
|
555
|
+
|
|
556
|
+
// Italic (*...*)
|
|
557
|
+
html = html.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, '<i>$1</i>');
|
|
558
|
+
|
|
559
|
+
// Links [text](url)
|
|
560
|
+
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
|
|
561
|
+
|
|
562
|
+
return html;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Smart text splitting — prefer paragraph boundaries (blank lines) before hard length split.
|
|
567
|
+
* Aligned with OpenClaw's chunkMode="newline" behavior.
|
|
568
|
+
*/
|
|
569
|
+
private smartSplit(text: string, maxLen: number): string[] {
|
|
570
|
+
if (text.length <= maxLen) return [text];
|
|
571
|
+
|
|
572
|
+
const parts: string[] = [];
|
|
573
|
+
let remaining = text;
|
|
574
|
+
|
|
575
|
+
while (remaining.length > maxLen) {
|
|
576
|
+
// Try to find a paragraph break (double newline) near the limit
|
|
577
|
+
let splitAt = remaining.lastIndexOf('\n\n', maxLen);
|
|
578
|
+
if (splitAt < maxLen * 0.3) {
|
|
579
|
+
// No good paragraph break, try single newline
|
|
580
|
+
splitAt = remaining.lastIndexOf('\n', maxLen);
|
|
581
|
+
}
|
|
582
|
+
if (splitAt < maxLen * 0.3) {
|
|
583
|
+
// No good newline, hard split at limit
|
|
584
|
+
splitAt = maxLen;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
parts.push(remaining.slice(0, splitAt).trimEnd());
|
|
588
|
+
remaining = remaining.slice(splitAt).trimStart();
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (remaining) parts.push(remaining);
|
|
592
|
+
return parts;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
private async apiCall(method: string, body?: Record<string, unknown>): Promise<any> {
|
|
596
|
+
const url = `https://api.telegram.org/bot${this.token}/${method}`;
|
|
597
|
+
try {
|
|
598
|
+
const res = await fetch(url, {
|
|
599
|
+
method: 'POST',
|
|
600
|
+
headers: { 'Content-Type': 'application/json' },
|
|
601
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
602
|
+
});
|
|
603
|
+
const data = await res.json() as { ok: boolean; result?: any; description?: string };
|
|
604
|
+
if (!data.ok) {
|
|
605
|
+
const err = new Error(`Telegram API ${method} failed: ${data.description}`);
|
|
606
|
+
(err as any).telegramError = data;
|
|
607
|
+
throw err;
|
|
608
|
+
}
|
|
609
|
+
return data;
|
|
610
|
+
} catch (err) {
|
|
611
|
+
if ((err as any).telegramError) throw err;
|
|
612
|
+
console.error(`[TelegramChannel] API call ${method} failed:`, err);
|
|
613
|
+
throw err;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|