@michengai/dsh-im-connect 0.1.68 → 0.1.71
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/CHANGELOG.md +19 -1
- package/CHANGELOG.zh-CN.md +19 -1
- package/README.md +37 -15
- package/README.zh-CN.md +38 -15
- package/SECURITY.md +2 -2
- package/assets/brands/discord-symbol.svg +3 -0
- package/assets/brands/slack-hash.png +0 -0
- package/assets/brands/slack-hash.svg +6 -0
- package/assets/brands//346/235/245/346/272/220.txt +14 -0
- package/client.js +72 -23
- package/lib/channels/channel-image-download.d.ts +3 -1
- package/lib/channels/channel-image-download.d.ts.map +1 -1
- package/lib/channels/channel-image-download.js +37 -3
- package/lib/channels/channel-image-download.js.map +1 -1
- package/lib/channels/factory.d.ts.map +1 -1
- package/lib/channels/factory.js +4 -0
- package/lib/channels/factory.js.map +1 -1
- package/lib/channels/meta.d.ts.map +1 -1
- package/lib/channels/meta.js +11 -0
- package/lib/channels/meta.js.map +1 -1
- package/lib/channels/slack-markdown.d.ts +34 -0
- package/lib/channels/slack-markdown.d.ts.map +1 -0
- package/lib/channels/slack-markdown.js +161 -0
- package/lib/channels/slack-markdown.js.map +1 -0
- package/lib/channels/slack.d.ts +106 -0
- package/lib/channels/slack.d.ts.map +1 -0
- package/lib/channels/slack.js +804 -0
- package/lib/channels/slack.js.map +1 -0
- package/lib/client.js +72 -23
- package/lib/engine/session-id.d.ts +1 -1
- package/lib/engine/session-id.d.ts.map +1 -1
- package/lib/engine/session-id.js +1 -1
- package/lib/engine/session-id.js.map +1 -1
- package/lib/manager.d.ts +3 -0
- package/lib/manager.d.ts.map +1 -1
- package/lib/manager.js +35 -1
- package/lib/manager.js.map +1 -1
- package/package.json +1 -1
- package/src/channels/channel-image-download.ts +30 -2
- package/src/channels/factory.ts +3 -0
- package/src/channels/meta.ts +11 -0
- package/src/channels/slack-markdown.ts +162 -0
- package/src/channels/slack.ts +828 -0
- package/src/engine/session-id.ts +2 -2
- package/src/manager.ts +27 -1
|
@@ -0,0 +1,804 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slack:Socket Mode 长连接(WebSocket)+ Web API。
|
|
3
|
+
*
|
|
4
|
+
* 私聊直接回复;频道与群聊里只有被 @ 才响应,并且在该消息的线程内回复,避免刷屏。
|
|
5
|
+
* 传输只用 Node 自带的 WebSocket 与 fetch,与 Discord、QQ 渠道保持一致,不引入平台 SDK。
|
|
6
|
+
*/
|
|
7
|
+
import { choiceSendError } from '../engine/choice-delivery.js';
|
|
8
|
+
import { channelNotice } from '../engine/command-locale.js';
|
|
9
|
+
import { sleepWithSignal, timeoutSignal } from '../engine/abort.js';
|
|
10
|
+
import { splitText } from '../engine/split.js';
|
|
11
|
+
import { DiagnosticError, diagnosticJson, probe, requireDiagnostic } from './diagnostics.js';
|
|
12
|
+
import { fileMedia, imageMedia, MAX_CHANNEL_IMAGE_BYTES, MAX_CHANNEL_IMAGES, requestChannelBytes } from './channel-image-download.js';
|
|
13
|
+
import { prepareSlackText, slackInboundText, slackMentionsBot } from './slack-markdown.js';
|
|
14
|
+
import { fileForm } from './file-send.js';
|
|
15
|
+
import { JsonStateFile } from '../engine/json-state.js';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
const API = 'https://slack.com/api/';
|
|
18
|
+
const MESSAGE_LIMIT = 4_000;
|
|
19
|
+
const SECTION_LIMIT = 2_900;
|
|
20
|
+
const FILE_LIMIT = 20 * 1024 * 1024;
|
|
21
|
+
const MAX_BUTTONS = 25;
|
|
22
|
+
const BUTTON_TEXT_LIMIT = 75;
|
|
23
|
+
const FLUSH_INTERVAL_MS = 1_100;
|
|
24
|
+
const SEEN_TTL_MS = 5 * 60_000;
|
|
25
|
+
const RECONNECT_DELAYS = [1_000, 3_000, 5_000, 10_000, 30_000];
|
|
26
|
+
/** url_private 只允许 Slack 自己的文件域名,令牌不能跟着任意地址走。 */
|
|
27
|
+
const FILE_HOSTS = new Set(['files.slack.com']);
|
|
28
|
+
/** 事件里只处理这几种消息子类型,其余(编辑、撤回、入群等)不驱动 agent。 */
|
|
29
|
+
const MESSAGE_SUBTYPES = new Set(['file_share', 'thread_broadcast']);
|
|
30
|
+
const AUTH_ERRORS = new Set(['invalid_auth', 'not_authed', 'account_inactive', 'token_revoked', 'invalid_refresh_token', 'not_allowed_token_type', 'missing_scope']);
|
|
31
|
+
const CHANNEL_ID = /^[A-Za-z0-9]{2,32}$/;
|
|
32
|
+
const MESSAGE_TS = /^\d{1,20}\.\d{1,10}$/;
|
|
33
|
+
/** Bot Token 必须是 xoxb-。用户令牌 xoxp- 会绕过机器人身份,不接受。App-Level Token 固定 xapp-。 */
|
|
34
|
+
const BOT_TOKEN_PREFIX = /^xoxb-/;
|
|
35
|
+
const APP_TOKEN_PREFIX = /^xapp-/;
|
|
36
|
+
const BOT_TOKEN_HINT = 'Slack Bot Token 不对:请在 Slack 应用的 OAuth & Permissions 页面安装应用后,复制 Bot User OAuth Token(xoxb- 开头)。App ID、Client ID、Client Secret、Signing Secret、Verification Token 都不是这个字段要填的内容。';
|
|
37
|
+
const APP_TOKEN_HINT = 'Slack App Token 不对:请在 Slack 应用的 Socket Mode 页面点 Generate Token and Scopes 生成 App-Level Token(xapp- 开头,勾 connections:write),它只显示一次。';
|
|
38
|
+
function credentialError(message) {
|
|
39
|
+
return Object.assign(new Error(message), { rejected: true, code: 'slack-401', status: 401 });
|
|
40
|
+
}
|
|
41
|
+
function codePoints(value) {
|
|
42
|
+
return [...value];
|
|
43
|
+
}
|
|
44
|
+
function clip(value, limit) {
|
|
45
|
+
return codePoints(value).slice(0, limit).join('');
|
|
46
|
+
}
|
|
47
|
+
function errorMessage(error) {
|
|
48
|
+
return error instanceof Error ? error.message : String(error);
|
|
49
|
+
}
|
|
50
|
+
/** chatId 是渠道不透明标识:频道号 + 线程根。 */
|
|
51
|
+
export function slackChatId(channel, threadTs) {
|
|
52
|
+
return threadTs ? `${channel}~${threadTs}` : channel;
|
|
53
|
+
}
|
|
54
|
+
export function parseSlackChatId(chatId) {
|
|
55
|
+
const index = chatId.indexOf('~');
|
|
56
|
+
const channel = index < 0 ? chatId : chatId.slice(0, index);
|
|
57
|
+
const threadTs = index < 0 ? undefined : chatId.slice(index + 1);
|
|
58
|
+
if (!CHANNEL_ID.test(channel) || (threadTs !== undefined && !MESSAGE_TS.test(threadTs))) {
|
|
59
|
+
throw Object.assign(new Error('slack-invalid-chat'), { rejected: true });
|
|
60
|
+
}
|
|
61
|
+
return threadTs === undefined ? { channel } : { channel, threadTs };
|
|
62
|
+
}
|
|
63
|
+
export function slackChatKind(channelId, channelName) {
|
|
64
|
+
return channelId.startsWith('D') || channelName === 'directmessage' ? 'dm' : 'group';
|
|
65
|
+
}
|
|
66
|
+
export function slackSocketUrl(value) {
|
|
67
|
+
const url = new URL(String(value ?? ''));
|
|
68
|
+
const host = url.hostname.toLowerCase();
|
|
69
|
+
if (url.protocol !== 'wss:' || url.username || url.password || (host !== 'slack.com' && !host.endsWith('.slack.com'))) {
|
|
70
|
+
throw new Error('Slack Socket Mode URL is invalid');
|
|
71
|
+
}
|
|
72
|
+
return url.href;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Slack 客户端会拦截半角 /。已知命令可用 !help 或全角 /help 发出,规则与 Discord 相同;未知感叹号保持原文。
|
|
76
|
+
*/
|
|
77
|
+
const SLACK_BANG_COMMANDS = new Set(['menu', 'm', 'new', 'clear', 'stop', 'status', 'help', 'sessions', 'models', 'export']);
|
|
78
|
+
export function normalizeSlackCommand(text) {
|
|
79
|
+
const match = /^[!/]([a-z][a-z0-9_-]*)(\s*[\s\S]*)$/i.exec(text.trim());
|
|
80
|
+
const command = match?.[1]?.toLowerCase();
|
|
81
|
+
if (!command || !SLACK_BANG_COMMANDS.has(command))
|
|
82
|
+
return text;
|
|
83
|
+
const name = command === 'm' ? 'menu' : command;
|
|
84
|
+
return `/${name}${match?.[2] ?? ''}`;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* 事件 → 收件目标。返回 undefined 表示这条事件不该驱动 agent。
|
|
88
|
+
* 频道消息在「被 @」、所在线程已经参与过,或用 ! / 全角斜杠发出已知命令时算被呼叫。
|
|
89
|
+
*/
|
|
90
|
+
export function slackRoute(event, botUserId, knownThreads) {
|
|
91
|
+
if (event.type !== 'message' && event.type !== 'app_mention')
|
|
92
|
+
return undefined;
|
|
93
|
+
if (event.hidden === true)
|
|
94
|
+
return undefined;
|
|
95
|
+
if (event.subtype !== undefined && !MESSAGE_SUBTYPES.has(event.subtype))
|
|
96
|
+
return undefined;
|
|
97
|
+
if (event.bot_id || !event.channel || !CHANNEL_ID.test(event.channel) || !event.ts || !MESSAGE_TS.test(event.ts))
|
|
98
|
+
return undefined;
|
|
99
|
+
const userId = typeof event.user === 'string' ? event.user : '';
|
|
100
|
+
if (!userId || userId === botUserId)
|
|
101
|
+
return undefined;
|
|
102
|
+
const direct = event.channel_type === 'im';
|
|
103
|
+
const mentioned = event.type === 'app_mention' || slackMentionsBot(event.text, botUserId);
|
|
104
|
+
const inbound = slackInboundText(event.text ?? '', botUserId);
|
|
105
|
+
const text = normalizeSlackCommand(inbound);
|
|
106
|
+
const prefixed = text.startsWith('/') && text !== inbound;
|
|
107
|
+
const threadRoot = direct ? undefined : (event.thread_ts && MESSAGE_TS.test(event.thread_ts) ? event.thread_ts : event.ts);
|
|
108
|
+
const threadKey = threadRoot === event.ts ? `${event.channel}~${event.ts}` : `${event.channel}~${threadRoot ?? ''}`;
|
|
109
|
+
const inKnownThread = !direct && Boolean(event.thread_ts) && Boolean(knownThreads?.has(threadKey));
|
|
110
|
+
if (!direct && !mentioned && !inKnownThread && !prefixed)
|
|
111
|
+
return undefined;
|
|
112
|
+
return {
|
|
113
|
+
chatId: slackChatId(event.channel, threadRoot),
|
|
114
|
+
channel: event.channel,
|
|
115
|
+
...(threadRoot ? { threadTs: threadRoot } : {}),
|
|
116
|
+
kind: direct ? 'dm' : 'group',
|
|
117
|
+
addressed: direct || mentioned || inKnownThread || prefixed,
|
|
118
|
+
userId,
|
|
119
|
+
...(event.username ? { username: event.username } : {}),
|
|
120
|
+
text,
|
|
121
|
+
messageId: event.ts,
|
|
122
|
+
...(direct ? {} : { threadKey }),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** 卡片按钮回调 → 收件目标。 */
|
|
126
|
+
export function slackActionRoute(payload) {
|
|
127
|
+
if (payload.type !== 'block_actions')
|
|
128
|
+
return undefined;
|
|
129
|
+
const action = payload.actions?.[0];
|
|
130
|
+
const token = action?.action_id ?? action?.value;
|
|
131
|
+
const channel = payload.container?.channel_id ?? payload.channel?.id;
|
|
132
|
+
const userId = payload.user?.id;
|
|
133
|
+
if (!token || typeof channel !== 'string' || !CHANNEL_ID.test(channel) || typeof userId !== 'string' || !userId)
|
|
134
|
+
return undefined;
|
|
135
|
+
const threadTs = payload.message?.thread_ts && MESSAGE_TS.test(payload.message.thread_ts)
|
|
136
|
+
? payload.message.thread_ts
|
|
137
|
+
: payload.container?.thread_ts && MESSAGE_TS.test(payload.container.thread_ts) ? payload.container.thread_ts : undefined;
|
|
138
|
+
const ts = payload.message?.ts && MESSAGE_TS.test(payload.message.ts) ? payload.message.ts : '';
|
|
139
|
+
return {
|
|
140
|
+
chatId: slackChatId(channel, threadTs),
|
|
141
|
+
channel,
|
|
142
|
+
...(threadTs ? { threadTs } : {}),
|
|
143
|
+
kind: slackChatKind(channel, payload.channel?.name),
|
|
144
|
+
addressed: true,
|
|
145
|
+
userId,
|
|
146
|
+
...(payload.user?.username ?? payload.user?.name ? { username: payload.user?.username ?? payload.user?.name } : {}),
|
|
147
|
+
text: '',
|
|
148
|
+
messageId: `interaction:${ts || channel}`,
|
|
149
|
+
actionToken: token,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function slackError(method, status, code) {
|
|
153
|
+
const auth = status === 401 || (code !== undefined && AUTH_ERRORS.has(code));
|
|
154
|
+
// 网关响应缺失或服务器内部错误不能证明请求未执行,不能据此自动补发。
|
|
155
|
+
const uncertain = new Set(['invalid_response', 'internal_error', 'fatal_error', 'request_timeout', 'service_unavailable']);
|
|
156
|
+
const rejected = (status >= 400 && status < 500 && status !== 408)
|
|
157
|
+
|| (status >= 200 && status < 300 && code !== undefined && !uncertain.has(code));
|
|
158
|
+
return Object.assign(new Error(`slack-${method}-${code ?? status}`), {
|
|
159
|
+
status,
|
|
160
|
+
...(code === undefined ? {} : { slackCode: code }),
|
|
161
|
+
rejected,
|
|
162
|
+
...(auth ? { code: 'slack-401' } : {}),
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/** 令牌失效、缺少授权范围不会自愈,重连也没有意义。 */
|
|
166
|
+
function fatalSlack(error) {
|
|
167
|
+
const value = error;
|
|
168
|
+
if (value?.code === 'slack-401' || value?.status === 401 || value?.status === 403)
|
|
169
|
+
return true;
|
|
170
|
+
return value?.slackCode !== undefined && AUTH_ERRORS.has(value.slackCode);
|
|
171
|
+
}
|
|
172
|
+
function recoverableSlack(error) {
|
|
173
|
+
if (fatalSlack(error))
|
|
174
|
+
return false;
|
|
175
|
+
const status = error?.status;
|
|
176
|
+
if (status === undefined)
|
|
177
|
+
return true;
|
|
178
|
+
return status === 429 || status >= 500;
|
|
179
|
+
}
|
|
180
|
+
/** 带 blocks 的消息只渲染块,纯 text 会退化成通知文案,所以正文必须自己放进 section 块。 */
|
|
181
|
+
function sectionBlocks(text) {
|
|
182
|
+
return splitText(text || '…', SECTION_LIMIT).map((part) => ({
|
|
183
|
+
type: 'section', text: { type: 'mrkdwn', text: part },
|
|
184
|
+
}));
|
|
185
|
+
}
|
|
186
|
+
function actionBlocks(buttons) {
|
|
187
|
+
const blocks = [];
|
|
188
|
+
for (let index = 0; index < buttons.length; index += 5) {
|
|
189
|
+
blocks.push({
|
|
190
|
+
type: 'actions',
|
|
191
|
+
elements: buttons.slice(index, index + 5).map((button) => ({
|
|
192
|
+
type: 'button',
|
|
193
|
+
text: { type: 'plain_text', text: clip(button.label, BUTTON_TEXT_LIMIT) || '…', emoji: true },
|
|
194
|
+
action_id: clip(button.token, 255),
|
|
195
|
+
value: clip(button.token, 2_000),
|
|
196
|
+
})),
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return blocks;
|
|
200
|
+
}
|
|
201
|
+
export function createSlackChannel(config, log) {
|
|
202
|
+
const token = config.token?.trim();
|
|
203
|
+
const appToken = config.appToken?.trim();
|
|
204
|
+
if (!token || !appToken)
|
|
205
|
+
return undefined;
|
|
206
|
+
const fetchImpl = config.fetchImpl ?? fetch;
|
|
207
|
+
const apiBase = `${(config.apiBase ?? API).replace(/\/+$/, '')}/`;
|
|
208
|
+
const createSocket = config.createWebSocket ?? ((url) => new WebSocket(url));
|
|
209
|
+
let handler;
|
|
210
|
+
let stopped = true;
|
|
211
|
+
let starting = false;
|
|
212
|
+
let readyOnce = false;
|
|
213
|
+
let statusText = '已停止';
|
|
214
|
+
let lifecycle = new AbortController();
|
|
215
|
+
let socket;
|
|
216
|
+
let generation = 0;
|
|
217
|
+
let reconnectAttempt = 0;
|
|
218
|
+
let haltReconnect = false;
|
|
219
|
+
let reconnectTimer;
|
|
220
|
+
let botUserId = '';
|
|
221
|
+
let botId = '';
|
|
222
|
+
/** Slack 会同时投递 app_mention 与 message 事件,按 channel+ts 去重。 */
|
|
223
|
+
const seenEvents = new Map();
|
|
224
|
+
/** 参与过的线程:后续没被 @ 的线程回复也要继续响应。 */
|
|
225
|
+
const participatedThreads = new Map();
|
|
226
|
+
const threadFile = config.stateDir
|
|
227
|
+
? new JsonStateFile(join(config.stateDir, 'slack-threads.json'), {})
|
|
228
|
+
: undefined;
|
|
229
|
+
function restoreThreads(identity) {
|
|
230
|
+
if (botUserId !== identity)
|
|
231
|
+
participatedThreads.clear();
|
|
232
|
+
const saved = threadFile?.read();
|
|
233
|
+
if (saved?.botUserId !== identity || !Array.isArray(saved.threads))
|
|
234
|
+
return;
|
|
235
|
+
for (const key of saved.threads.slice(-512)) {
|
|
236
|
+
if (typeof key !== 'string')
|
|
237
|
+
continue;
|
|
238
|
+
try {
|
|
239
|
+
const route = parseSlackChatId(key);
|
|
240
|
+
if (route.threadTs)
|
|
241
|
+
participatedThreads.set(key, Number.POSITIVE_INFINITY);
|
|
242
|
+
}
|
|
243
|
+
catch { /* 忽略损坏的线程记录,不能扩大免提及范围。 */ }
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function prune(store) {
|
|
247
|
+
const now = Date.now();
|
|
248
|
+
for (const [key, expires] of store)
|
|
249
|
+
if (expires <= now)
|
|
250
|
+
store.delete(key);
|
|
251
|
+
while (store.size > 512)
|
|
252
|
+
store.delete(store.keys().next().value);
|
|
253
|
+
}
|
|
254
|
+
function rememberThread(key) {
|
|
255
|
+
participatedThreads.delete(key);
|
|
256
|
+
participatedThreads.set(key, Number.POSITIVE_INFINITY);
|
|
257
|
+
while (participatedThreads.size > 512)
|
|
258
|
+
participatedThreads.delete(participatedThreads.keys().next().value);
|
|
259
|
+
if (threadFile) {
|
|
260
|
+
try {
|
|
261
|
+
threadFile.write({ botUserId, threads: [...participatedThreads.keys()] });
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
log('[slack] 参与线程记录保存失败,重启后可能需要重新 @机器人');
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function firstSight(store, key) {
|
|
269
|
+
prune(store);
|
|
270
|
+
if (store.has(key))
|
|
271
|
+
return false;
|
|
272
|
+
store.set(key, Date.now() + SEEN_TTL_MS);
|
|
273
|
+
return true;
|
|
274
|
+
}
|
|
275
|
+
async function api(method, body = {}, options = {}) {
|
|
276
|
+
const credential = options.token ?? token;
|
|
277
|
+
for (let attempt = 0;; attempt += 1) {
|
|
278
|
+
const response = await fetchImpl(`${apiBase}${method}`, {
|
|
279
|
+
method: 'POST',
|
|
280
|
+
headers: { 'content-type': 'application/json; charset=utf-8', authorization: `Bearer ${credential}` },
|
|
281
|
+
body: JSON.stringify(body),
|
|
282
|
+
signal: timeoutSignal(options.timeoutMs ?? 30_000, AbortSignal.any([...(options.signal ? [options.signal] : []), lifecycle.signal])),
|
|
283
|
+
redirect: 'error',
|
|
284
|
+
});
|
|
285
|
+
// Slack 的频道级限流按秒计,重试一次比把失败抛给用户更合适。
|
|
286
|
+
if (response.status === 429 && attempt === 0) {
|
|
287
|
+
const wait = Math.min(Math.max(Number(response.headers.get('retry-after')) || 1, 1), 5);
|
|
288
|
+
await response.body?.cancel().catch(() => undefined);
|
|
289
|
+
await sleepWithSignal(wait * 1_000, lifecycle.signal).catch(() => undefined);
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const payload = await response.json().catch(() => undefined);
|
|
293
|
+
// 代理返回的 HTML 页面也是 200:没有 JSON 就不能当成功。
|
|
294
|
+
if (!payload || typeof payload !== 'object' || typeof payload.ok !== 'boolean')
|
|
295
|
+
throw slackError(method, response.status, 'invalid_response');
|
|
296
|
+
if (!response.ok)
|
|
297
|
+
throw slackError(method, response.status, typeof payload.error === 'string' ? payload.error : undefined);
|
|
298
|
+
if (payload.ok === false)
|
|
299
|
+
throw slackError(method, response.status, payload.error);
|
|
300
|
+
return payload;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
function sendAck(envelopeId) {
|
|
304
|
+
try {
|
|
305
|
+
socket?.send(JSON.stringify({ envelope_id: envelopeId }));
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
log('[slack] 事件确认失败');
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
function authorizedFileUrl(value) {
|
|
312
|
+
const url = new URL(String(value ?? ''));
|
|
313
|
+
if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443') || !FILE_HOSTS.has(url.hostname.toLowerCase())) {
|
|
314
|
+
throw new Error('图片地址不符合安全要求');
|
|
315
|
+
}
|
|
316
|
+
return url.href;
|
|
317
|
+
}
|
|
318
|
+
async function loadMedia(event) {
|
|
319
|
+
const files = (event.files ?? []).slice(0, MAX_CHANNEL_IMAGES);
|
|
320
|
+
const media = [];
|
|
321
|
+
for (const file of files) {
|
|
322
|
+
const raw = typeof file.url_private_download === 'string' ? file.url_private_download
|
|
323
|
+
: typeof file.url_private === 'string' ? file.url_private : '';
|
|
324
|
+
if (!raw)
|
|
325
|
+
continue;
|
|
326
|
+
const isImage = typeof file.mimetype === 'string' && file.mimetype.startsWith('image/');
|
|
327
|
+
const maxBytes = isImage ? MAX_CHANNEL_IMAGE_BYTES : FILE_LIMIT;
|
|
328
|
+
if (typeof file.size === 'number' && file.size > maxBytes)
|
|
329
|
+
throw new Error('文件超过大小限制');
|
|
330
|
+
const data = await requestChannelBytes(authorizedFileUrl(raw), {
|
|
331
|
+
headers: { authorization: `Bearer ${token}` },
|
|
332
|
+
maxBytes,
|
|
333
|
+
timeoutMs: 30_000,
|
|
334
|
+
signal: AbortSignal.any([lifecycle.signal, AbortSignal.timeout(60_000)]),
|
|
335
|
+
sameHostRedirects: 3,
|
|
336
|
+
});
|
|
337
|
+
const head = data.subarray(0, 32).toString('utf8').trimStart().toLowerCase();
|
|
338
|
+
if (head.startsWith('<!doctype') || head.startsWith('<html'))
|
|
339
|
+
throw new Error('图片地址不符合安全要求');
|
|
340
|
+
media.push(isImage ? imageMedia(data) : fileMedia(data, file.name ?? 'file.bin'));
|
|
341
|
+
}
|
|
342
|
+
return media;
|
|
343
|
+
}
|
|
344
|
+
async function postMessage(chatId, text, signal, blocks) {
|
|
345
|
+
const route = parseSlackChatId(chatId);
|
|
346
|
+
return api('chat.postMessage', {
|
|
347
|
+
channel: route.channel,
|
|
348
|
+
text,
|
|
349
|
+
mrkdwn: true,
|
|
350
|
+
unfurl_links: false,
|
|
351
|
+
unfurl_media: false,
|
|
352
|
+
...(route.threadTs ? { thread_ts: route.threadTs } : {}),
|
|
353
|
+
...(blocks ? { blocks } : {}),
|
|
354
|
+
}, { signal });
|
|
355
|
+
}
|
|
356
|
+
async function acceptEvent(event) {
|
|
357
|
+
const route = slackRoute(event, botUserId, participatedThreads);
|
|
358
|
+
if (!route)
|
|
359
|
+
return;
|
|
360
|
+
if (!firstSight(seenEvents, `${route.channel}:${route.messageId}`))
|
|
361
|
+
return;
|
|
362
|
+
if (route.threadKey)
|
|
363
|
+
rememberThread(route.threadKey);
|
|
364
|
+
let media = [];
|
|
365
|
+
if (event.files?.length) {
|
|
366
|
+
try {
|
|
367
|
+
media = await loadMedia(event);
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
if (stopped)
|
|
371
|
+
return;
|
|
372
|
+
// 失败原因可能带签名地址,只写本机日志;聊天里给固定文案。
|
|
373
|
+
log('[slack] 图片或文件接收失败');
|
|
374
|
+
await postMessage(route.chatId, channelNotice(config.host, '图片或文件接收失败,请检查格式和大小后重新发送完整消息。'), undefined, undefined)
|
|
375
|
+
.catch(() => log('[slack] 失败提示发送失败'));
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (stopped)
|
|
380
|
+
return;
|
|
381
|
+
await handler?.({
|
|
382
|
+
chatId: route.chatId,
|
|
383
|
+
userId: route.userId,
|
|
384
|
+
...(route.username ? { username: route.username } : {}),
|
|
385
|
+
text: route.text,
|
|
386
|
+
...(media.length ? { media } : {}),
|
|
387
|
+
kind: route.kind,
|
|
388
|
+
addressed: route.addressed,
|
|
389
|
+
messageId: route.messageId,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
async function acceptEnvelope(envelope) {
|
|
393
|
+
if (envelope.type === 'events_api') {
|
|
394
|
+
const payload = envelope.payload;
|
|
395
|
+
if (payload?.event)
|
|
396
|
+
await acceptEvent(payload.event);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
if (envelope.type === 'interactive') {
|
|
400
|
+
const route = slackActionRoute(envelope.payload);
|
|
401
|
+
if (!route)
|
|
402
|
+
return;
|
|
403
|
+
await handler?.({
|
|
404
|
+
chatId: route.chatId,
|
|
405
|
+
userId: route.userId,
|
|
406
|
+
...(route.username ? { username: route.username } : {}),
|
|
407
|
+
text: '',
|
|
408
|
+
kind: route.kind,
|
|
409
|
+
addressed: true,
|
|
410
|
+
messageId: route.messageId,
|
|
411
|
+
...(route.actionToken ? { actionToken: route.actionToken } : {}),
|
|
412
|
+
});
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
if (envelope.type === 'slash_commands') {
|
|
416
|
+
const payload = envelope.payload;
|
|
417
|
+
const channel = payload?.channel_id;
|
|
418
|
+
const userId = payload?.user_id;
|
|
419
|
+
if (typeof channel !== 'string' || !CHANNEL_ID.test(channel) || typeof userId !== 'string' || !userId || userId === botUserId)
|
|
420
|
+
return;
|
|
421
|
+
const kind = slackChatKind(channel, payload?.channel_name);
|
|
422
|
+
const command = (payload?.command ?? '').trim().replace(/^\//, '');
|
|
423
|
+
const text = `/${command}${payload?.text ? ` ${payload.text}` : ''}`.trim();
|
|
424
|
+
const trigger = typeof payload?.trigger_id === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(payload.trigger_id)
|
|
425
|
+
? payload.trigger_id
|
|
426
|
+
: envelope.envelope_id || `${channel}:${Date.now()}`;
|
|
427
|
+
// 必须先去重再发送线程根,网关的去重发生在这些副作用之后。
|
|
428
|
+
if (!firstSight(seenEvents, `slash:${trigger}`))
|
|
429
|
+
return;
|
|
430
|
+
let threadTs = kind === 'group' && payload?.thread_ts && MESSAGE_TS.test(payload.thread_ts) ? payload.thread_ts : undefined;
|
|
431
|
+
if (kind === 'group' && !threadTs) {
|
|
432
|
+
const opened = await postMessage(slackChatId(channel), text);
|
|
433
|
+
threadTs = opened.ts && MESSAGE_TS.test(opened.ts) ? opened.ts : undefined;
|
|
434
|
+
if (!threadTs)
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
if (kind === 'group' && threadTs)
|
|
438
|
+
rememberThread(`${channel}~${threadTs}`);
|
|
439
|
+
await handler?.({
|
|
440
|
+
chatId: slackChatId(channel, threadTs),
|
|
441
|
+
userId,
|
|
442
|
+
...(payload?.user_name ? { username: payload.user_name } : {}),
|
|
443
|
+
text,
|
|
444
|
+
kind,
|
|
445
|
+
addressed: true,
|
|
446
|
+
messageId: `slash:${trigger}`,
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
async function openSocket() {
|
|
451
|
+
// apps.connections.open 用 App-Level Token,其余 Web API 调用用 Bot Token。
|
|
452
|
+
const opened = await api('apps.connections.open', {}, { token: appToken, timeoutMs: 15_000 });
|
|
453
|
+
const target = slackSocketUrl(opened.url);
|
|
454
|
+
const current = createSocket(target);
|
|
455
|
+
socket = current;
|
|
456
|
+
const currentGeneration = generation;
|
|
457
|
+
await new Promise((resolve, reject) => {
|
|
458
|
+
let settled = false;
|
|
459
|
+
const finish = (error) => {
|
|
460
|
+
if (settled)
|
|
461
|
+
return;
|
|
462
|
+
settled = true;
|
|
463
|
+
clearTimeout(timer);
|
|
464
|
+
if (error)
|
|
465
|
+
reject(error);
|
|
466
|
+
else
|
|
467
|
+
resolve();
|
|
468
|
+
};
|
|
469
|
+
const timer = setTimeout(() => {
|
|
470
|
+
statusText = readyOnce ? '重连中' : '连接中';
|
|
471
|
+
finish(new Error('slack-socket-timeout'));
|
|
472
|
+
try {
|
|
473
|
+
current.close(1000, 'timeout');
|
|
474
|
+
}
|
|
475
|
+
catch { /* 已经断开 */ }
|
|
476
|
+
}, config.connectTimeoutMs ?? 20_000);
|
|
477
|
+
current.addEventListener('message', (messageEvent) => {
|
|
478
|
+
if (stopped || currentGeneration !== generation)
|
|
479
|
+
return;
|
|
480
|
+
const raw = typeof messageEvent.data === 'string' ? messageEvent.data : '';
|
|
481
|
+
if (!raw)
|
|
482
|
+
return;
|
|
483
|
+
let envelope;
|
|
484
|
+
try {
|
|
485
|
+
envelope = JSON.parse(raw);
|
|
486
|
+
}
|
|
487
|
+
catch {
|
|
488
|
+
log('[slack] 忽略无法解析的事件帧');
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (envelope.type === 'hello') {
|
|
492
|
+
reconnectAttempt = 0;
|
|
493
|
+
readyOnce = true;
|
|
494
|
+
statusText = '长连接已建立';
|
|
495
|
+
finish();
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
if (envelope.type === 'disconnect') {
|
|
499
|
+
// refresh_requested 是 Slack 的正常轮换,重新连接即可;其余原因需要管理员处理。
|
|
500
|
+
const reason = typeof envelope.reason === 'string' ? envelope.reason : '';
|
|
501
|
+
if (reason === 'refresh_requested') {
|
|
502
|
+
try {
|
|
503
|
+
current.close(1000, 'refresh');
|
|
504
|
+
}
|
|
505
|
+
catch { /* 已经断开 */ }
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
if (reason === 'link_disabled') {
|
|
509
|
+
haltReconnect = true;
|
|
510
|
+
statusText = '连接失败,请查看本机日志';
|
|
511
|
+
log(`[slack] Socket Mode 已断开: ${reason}`);
|
|
512
|
+
clearTimeout(reconnectTimer);
|
|
513
|
+
try {
|
|
514
|
+
current.close(1000, 'disconnect');
|
|
515
|
+
}
|
|
516
|
+
catch { /* 已经断开 */ }
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
statusText = '连接失败,请查看本机日志';
|
|
520
|
+
log(`[slack] Socket Mode 已断开: ${reason || 'unknown'}`);
|
|
521
|
+
try {
|
|
522
|
+
current.close(1000, 'disconnect');
|
|
523
|
+
}
|
|
524
|
+
catch { /* 已经断开 */ }
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
// 事件必须在 3 秒内确认,且确认不能等业务处理完。
|
|
528
|
+
if (envelope.envelope_id)
|
|
529
|
+
sendAck(envelope.envelope_id);
|
|
530
|
+
void acceptEnvelope(envelope).catch((error) => log(`[slack] 事件处理失败: ${errorMessage(error)}`));
|
|
531
|
+
});
|
|
532
|
+
current.addEventListener('close', () => {
|
|
533
|
+
if (currentGeneration !== generation)
|
|
534
|
+
return;
|
|
535
|
+
if (socket === current)
|
|
536
|
+
socket = undefined;
|
|
537
|
+
if (haltReconnect) {
|
|
538
|
+
statusText = '连接失败,请查看本机日志';
|
|
539
|
+
finish(new Error('slack-link-disabled'));
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
if (stopped) {
|
|
543
|
+
finish(Object.assign(new Error('Stopped'), { name: 'AbortError' }));
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
statusText = readyOnce ? '重连中' : '连接中';
|
|
547
|
+
finish(new Error('slack-socket-closed'));
|
|
548
|
+
if (!starting)
|
|
549
|
+
scheduleReconnect();
|
|
550
|
+
});
|
|
551
|
+
current.addEventListener('error', () => {
|
|
552
|
+
if (currentGeneration === generation && !stopped)
|
|
553
|
+
log('[slack] Socket Mode WebSocket 错误');
|
|
554
|
+
});
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
function scheduleReconnect() {
|
|
558
|
+
clearTimeout(reconnectTimer);
|
|
559
|
+
const delay = RECONNECT_DELAYS[Math.min(reconnectAttempt, RECONNECT_DELAYS.length - 1)];
|
|
560
|
+
reconnectAttempt += 1;
|
|
561
|
+
reconnectTimer = setTimeout(() => {
|
|
562
|
+
if (stopped || haltReconnect)
|
|
563
|
+
return;
|
|
564
|
+
void openSocket().catch((error) => {
|
|
565
|
+
if (stopped || fatalSlack(error))
|
|
566
|
+
return;
|
|
567
|
+
log(`[slack] 重连失败: ${errorMessage(error)}`);
|
|
568
|
+
scheduleReconnect();
|
|
569
|
+
});
|
|
570
|
+
}, delay);
|
|
571
|
+
}
|
|
572
|
+
async function connectOnce() {
|
|
573
|
+
await openSocket();
|
|
574
|
+
}
|
|
575
|
+
return {
|
|
576
|
+
id: 'slack',
|
|
577
|
+
label: 'Slack',
|
|
578
|
+
maxMessageLength: MESSAGE_LIMIT,
|
|
579
|
+
choiceLimits: { maxButtons: MAX_BUTTONS, maxTextLength: 3_000 },
|
|
580
|
+
async start() {
|
|
581
|
+
await this.stop();
|
|
582
|
+
stopped = false;
|
|
583
|
+
starting = true;
|
|
584
|
+
readyOnce = false;
|
|
585
|
+
reconnectAttempt = 0;
|
|
586
|
+
statusText = '连接中';
|
|
587
|
+
lifecycle = new AbortController();
|
|
588
|
+
seenEvents.clear();
|
|
589
|
+
try {
|
|
590
|
+
// 先按前缀拦一次:Slack 应用页面上那五个 App Credentials 都不是这里要填的东西,
|
|
591
|
+
// 直接在日志里说清楚,比让 auth.test 回一个 invalid_auth 有用。
|
|
592
|
+
if (!BOT_TOKEN_PREFIX.test(token))
|
|
593
|
+
throw credentialError(BOT_TOKEN_HINT);
|
|
594
|
+
if (!APP_TOKEN_PREFIX.test(appToken))
|
|
595
|
+
throw credentialError(APP_TOKEN_HINT);
|
|
596
|
+
let identity;
|
|
597
|
+
try {
|
|
598
|
+
identity = await api('auth.test', {}, { timeoutMs: 15_000 });
|
|
599
|
+
}
|
|
600
|
+
catch (error) {
|
|
601
|
+
throw fatalSlack(error) ? credentialError(BOT_TOKEN_HINT) : error;
|
|
602
|
+
}
|
|
603
|
+
if (typeof identity.user_id !== 'string' || !identity.user_id)
|
|
604
|
+
throw credentialError(APP_TOKEN_HINT);
|
|
605
|
+
restoreThreads(identity.user_id);
|
|
606
|
+
botUserId = identity.user_id;
|
|
607
|
+
botId = typeof identity.bot_id === 'string' ? identity.bot_id : '';
|
|
608
|
+
await connectOnce();
|
|
609
|
+
starting = false;
|
|
610
|
+
log(`[slack] Socket Mode 已连接${botId ? `(${botId})` : ''}`);
|
|
611
|
+
}
|
|
612
|
+
catch (error) {
|
|
613
|
+
starting = false;
|
|
614
|
+
// 令牌或授权范围有问题时不停在重连,直接把失败交给管理器展示。
|
|
615
|
+
if (!recoverableSlack(error)) {
|
|
616
|
+
statusText = '连接失败,请查看本机日志';
|
|
617
|
+
await this.stop();
|
|
618
|
+
throw error;
|
|
619
|
+
}
|
|
620
|
+
statusText = '重连中';
|
|
621
|
+
log(`[slack] 启动时 Socket Mode 未就绪,将自动重连: ${errorMessage(error)}`);
|
|
622
|
+
scheduleReconnect();
|
|
623
|
+
}
|
|
624
|
+
finally {
|
|
625
|
+
starting = false;
|
|
626
|
+
}
|
|
627
|
+
},
|
|
628
|
+
async stop() {
|
|
629
|
+
stopped = true;
|
|
630
|
+
haltReconnect = false;
|
|
631
|
+
readyOnce = false;
|
|
632
|
+
statusText = '已停止';
|
|
633
|
+
clearTimeout(reconnectTimer);
|
|
634
|
+
generation += 1;
|
|
635
|
+
lifecycle.abort();
|
|
636
|
+
try {
|
|
637
|
+
socket?.close(1000, 'stopped');
|
|
638
|
+
}
|
|
639
|
+
catch { /* 已经断开 */ }
|
|
640
|
+
socket = undefined;
|
|
641
|
+
},
|
|
642
|
+
canDeliverDeferred() { return !stopped && statusText === '长连接已建立'; },
|
|
643
|
+
async send(chatId, text) {
|
|
644
|
+
const rendered = prepareSlackText(text);
|
|
645
|
+
const parts = codePoints(rendered).length <= MESSAGE_LIMIT ? [rendered] : splitText(rendered, MESSAGE_LIMIT);
|
|
646
|
+
for (const part of parts) {
|
|
647
|
+
if (part.trim() === '')
|
|
648
|
+
continue;
|
|
649
|
+
await postMessage(chatId, part);
|
|
650
|
+
}
|
|
651
|
+
},
|
|
652
|
+
async sendFile(chatId, file, signal) {
|
|
653
|
+
const route = parseSlackChatId(chatId);
|
|
654
|
+
const name = file.name.replace(/\\/g, '/').split('/').pop()?.replace(/[\x00-\x1f]/g, '').slice(0, 200) || 'file';
|
|
655
|
+
const abort = AbortSignal.any([...(signal ? [signal] : []), lifecycle.signal, AbortSignal.timeout(120_000)]);
|
|
656
|
+
const ticket = await api('files.getUploadURLExternal', {
|
|
657
|
+
filename: name,
|
|
658
|
+
length: file.data.byteLength,
|
|
659
|
+
}, { signal: abort });
|
|
660
|
+
const uploadUrl = typeof ticket.upload_url === 'string' ? ticket.upload_url : '';
|
|
661
|
+
const fileId = typeof ticket.file_id === 'string' ? ticket.file_id : '';
|
|
662
|
+
if (!uploadUrl || !fileId)
|
|
663
|
+
throw Object.assign(new Error('slack-upload-ticket'), { rejected: true });
|
|
664
|
+
const target = new URL(uploadUrl);
|
|
665
|
+
if (target.protocol !== 'https:' || !target.hostname.toLowerCase().endsWith('.slack.com'))
|
|
666
|
+
throw Object.assign(new Error('slack-upload-url'), { rejected: true });
|
|
667
|
+
const upload = await fetchImpl(uploadUrl, {
|
|
668
|
+
method: 'POST',
|
|
669
|
+
body: fileForm({ name, data: file.data }, 'file'),
|
|
670
|
+
signal: abort,
|
|
671
|
+
redirect: 'error',
|
|
672
|
+
});
|
|
673
|
+
if (!upload.ok) {
|
|
674
|
+
await upload.body?.cancel().catch(() => undefined);
|
|
675
|
+
throw Object.assign(new Error(`slack-upload-http-${upload.status}`), { status: upload.status });
|
|
676
|
+
}
|
|
677
|
+
await upload.body?.cancel().catch(() => undefined);
|
|
678
|
+
await api('files.completeUploadExternal', {
|
|
679
|
+
files: [{ id: fileId, title: name }],
|
|
680
|
+
channel_id: route.channel,
|
|
681
|
+
...(route.threadTs ? { thread_ts: route.threadTs } : {}),
|
|
682
|
+
}, { signal: abort });
|
|
683
|
+
},
|
|
684
|
+
async sendChoices(message, text, buttons) {
|
|
685
|
+
const rendered = prepareSlackText(text);
|
|
686
|
+
if (!buttons.length || buttons.length > MAX_BUTTONS || codePoints(rendered).length > MESSAGE_LIMIT) {
|
|
687
|
+
throw choiceSendError(Object.assign(new Error('slack-choice-limit'), { status: 400, rejected: true }));
|
|
688
|
+
}
|
|
689
|
+
try {
|
|
690
|
+
const route = parseSlackChatId(message.chatId);
|
|
691
|
+
const sent = await postMessage(message.chatId, rendered, undefined, [...sectionBlocks(rendered), ...actionBlocks(buttons)]);
|
|
692
|
+
if (!sent.ts)
|
|
693
|
+
return;
|
|
694
|
+
return {
|
|
695
|
+
close: async (status) => {
|
|
696
|
+
// 卡片只能改原消息:去掉按钮块,避免旧按钮被重复点击。
|
|
697
|
+
const body = `${rendered}\n\n${status}`;
|
|
698
|
+
await api('chat.update', {
|
|
699
|
+
channel: route.channel,
|
|
700
|
+
ts: sent.ts,
|
|
701
|
+
text: body,
|
|
702
|
+
blocks: sectionBlocks(body),
|
|
703
|
+
});
|
|
704
|
+
},
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
catch (error) {
|
|
708
|
+
throw choiceSendError(error);
|
|
709
|
+
}
|
|
710
|
+
},
|
|
711
|
+
async addStatusReaction(message, state, _label, signal) {
|
|
712
|
+
if (!message.messageId || state === 'cancelled' || message.messageId.startsWith('interaction:') || message.messageId.startsWith('slash:'))
|
|
713
|
+
return;
|
|
714
|
+
if (!MESSAGE_TS.test(message.messageId))
|
|
715
|
+
return;
|
|
716
|
+
const name = state === 'success' || state === 'ended' ? 'white_check_mark'
|
|
717
|
+
: state === 'error' ? 'x' : state === 'waiting' ? 'thinking_face' : 'eyes';
|
|
718
|
+
await api('reactions.add', { channel: parseSlackChatId(message.chatId).channel, timestamp: message.messageId, name }, { signal });
|
|
719
|
+
return name;
|
|
720
|
+
},
|
|
721
|
+
async removeStatusReaction(message, reaction, signal) {
|
|
722
|
+
if (!message.messageId || !reaction || message.messageId.startsWith('interaction:') || message.messageId.startsWith('slash:'))
|
|
723
|
+
return;
|
|
724
|
+
if (!MESSAGE_TS.test(message.messageId))
|
|
725
|
+
return;
|
|
726
|
+
await api('reactions.remove', { channel: parseSlackChatId(message.chatId).channel, timestamp: message.messageId, name: reaction }, { signal });
|
|
727
|
+
},
|
|
728
|
+
async beginReply(chatId) {
|
|
729
|
+
const route = parseSlackChatId(chatId);
|
|
730
|
+
const first = await postMessage(chatId, '…');
|
|
731
|
+
let last = '…';
|
|
732
|
+
let timer;
|
|
733
|
+
let pending;
|
|
734
|
+
let inflight = Promise.resolve();
|
|
735
|
+
const flush = async (text, allowSend) => {
|
|
736
|
+
const next = clip(text, MESSAGE_LIMIT) || '…';
|
|
737
|
+
if (next === last)
|
|
738
|
+
return;
|
|
739
|
+
try {
|
|
740
|
+
if (!first.ts)
|
|
741
|
+
throw Object.assign(new Error('slack-stream-missing-ts'), { rejected: true });
|
|
742
|
+
await api('chat.update', { channel: route.channel, ts: first.ts, text: next });
|
|
743
|
+
last = next;
|
|
744
|
+
}
|
|
745
|
+
catch (error) {
|
|
746
|
+
if (!allowSend)
|
|
747
|
+
return;
|
|
748
|
+
// 只有平台明确拒绝更新时才能补发;响应丢失时原消息可能已经更新。
|
|
749
|
+
if (choiceSendError(error).reason === 'delivery-unknown')
|
|
750
|
+
throw error;
|
|
751
|
+
await postMessage(chatId, next);
|
|
752
|
+
last = next;
|
|
753
|
+
}
|
|
754
|
+
};
|
|
755
|
+
return {
|
|
756
|
+
async update(text) {
|
|
757
|
+
pending = text;
|
|
758
|
+
if (timer)
|
|
759
|
+
return;
|
|
760
|
+
timer = setTimeout(() => {
|
|
761
|
+
timer = undefined;
|
|
762
|
+
const next = pending;
|
|
763
|
+
pending = undefined;
|
|
764
|
+
if (next !== undefined)
|
|
765
|
+
inflight = inflight.then(() => flush(prepareSlackText(next), false));
|
|
766
|
+
}, FLUSH_INTERVAL_MS);
|
|
767
|
+
},
|
|
768
|
+
async finish(text) {
|
|
769
|
+
if (timer)
|
|
770
|
+
clearTimeout(timer);
|
|
771
|
+
timer = undefined;
|
|
772
|
+
await inflight.catch(() => undefined);
|
|
773
|
+
const parts = splitText(prepareSlackText(text || pending || last), MESSAGE_LIMIT);
|
|
774
|
+
await flush(parts[0] || '…', true);
|
|
775
|
+
for (const part of parts.slice(1)) {
|
|
776
|
+
if (part.trim() === '')
|
|
777
|
+
continue;
|
|
778
|
+
await postMessage(chatId, part);
|
|
779
|
+
}
|
|
780
|
+
},
|
|
781
|
+
};
|
|
782
|
+
},
|
|
783
|
+
setMessageHandler(next) { handler = next; },
|
|
784
|
+
async diagnose(signal) {
|
|
785
|
+
const identity = await probe('bot', signal, async () => {
|
|
786
|
+
const data = await diagnosticJson(`${apiBase}auth.test`, signal, {}, { authorization: `Bearer ${token}` });
|
|
787
|
+
if (data.ok === false)
|
|
788
|
+
throw new DiagnosticError(AUTH_ERRORS.has(String(data.error)) ? 'auth' : 'rejected');
|
|
789
|
+
requireDiagnostic(data.ok === true && typeof data.user_id === 'string' && data.user_id);
|
|
790
|
+
});
|
|
791
|
+
if (identity.status !== 'passed')
|
|
792
|
+
return [identity];
|
|
793
|
+
if (!appToken || !readyOnce)
|
|
794
|
+
return [identity];
|
|
795
|
+
// 只读现有连接状态,不新建连接,也不发测试消息。
|
|
796
|
+
return [identity, await probe('gateway', signal, async () => {
|
|
797
|
+
if (stopped || statusText !== '长连接已建立')
|
|
798
|
+
throw new DiagnosticError('not-connected');
|
|
799
|
+
})];
|
|
800
|
+
},
|
|
801
|
+
status() { return statusText; },
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
//# sourceMappingURL=slack.js.map
|