Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Add the Slack and QQ IM adapters

Fei241167c618dad0f8
diff --git a/ds-bot/src/host/im/platforms/index.js b/ds-bot/src/host/im/platforms/index.js
index f865d364..c9d50a7a 100644
--- a/ds-bot/src/host/im/platforms/index.js
+++ b/ds-bot/src/host/im/platforms/index.js
@@ -1,6 +1,8 @@
import discord from './discord.js'
+import qq from './qq.js'
+import slack from './slack.js'
import telegram from './telegram.js'
// Every platform with an adapter. The rest of IM_PLATFORMS still show in settings as
// coming soon — a connection can only be added for a platform listed here.
-export const adapters = { telegram, discord }
+export const adapters = { telegram, discord, slack, qq }
diff --git a/ds-bot/src/host/im/platforms/qq.js b/ds-bot/src/host/im/platforms/qq.js
new file mode 100644
index 00000000..f7763213
--- /dev/null
+++ b/ds-bot/src/host/im/platforms/qq.js
@@ -0,0 +1,216 @@
+// QQ open platform: an app access token from appId+secret, then a Discord-like
+// gateway (hello, heartbeat, identify, resume, reconnect, invalid session) for
+// C2C and group @ messages. Sends are passive replies carrying the inbound
+// msg_id with an incrementing msg_seq; outside the reply window the platform
+// refuses and the reason is permanent. No buttons — the core numbers choices.
+// Wire details ported from @tencent-connect/qqbot-nodejs (MIT, see NOTICE).
+import { chunkMarkdown } from '../format.js'
+
+const API = 'https://api.sgroup.qq.com'
+const TOKEN_API = 'https://bots.qq.com'
+const TEXT_LIMIT = 2000
+// GROUP_AND_C2C covers C2C_MESSAGE_CREATE and GROUP_AT_MESSAGE_CREATE.
+const INTENTS = 1 << 25
+
+const apiBase = env => String(env.config?.api ?? API).replace(/\/+$/, '')
+const tokenBase = env => String(env.config?.token ?? apiBase(env))
+
+const getToken = async (fields, env) => {
+ const response = await env.fetch(`${tokenBase(env)}/app/getAppAccessToken`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ appId: String(fields.appId ?? '').trim(), clientSecret: String(fields.appSecret ?? '').trim() }),
+ })
+ const body = await response.json().catch(() => ({}))
+ if (body.access_token === undefined) throw new Error(body.error_reason ?? body.error ?? 'QQ refused these credentials')
+ return { token: body.access_token, expiresAt: Date.now() + Math.max(10, Number(body.expires_in ?? 7200) - 300) * 1000 }
+}
+
+export default {
+ id: 'qq',
+
+ async check(fields, env) {
+ const { token } = await getToken(fields, env)
+ const me = await api(env, token, '/users/@me', { method: 'GET' }).catch(() => ({}))
+ return { account: { id: String(fields.appId).trim(), name: me?.username ? `@${me.username}` : String(fields.appId).trim() } }
+ },
+
+ connect(fields, env, handlers) {
+ let stopped = false
+ let socket
+ let token
+ let expiresAt = 0
+ let refreshTimer
+ let heartbeatTimer
+ let heartbeatAcked = true
+ let reconnectTimer
+ let generation = 0
+ let sequence
+ let sessionId
+ // Passive replies reuse the inbound msg_id with a msg_seq that climbs
+ // per id — outside the window the platform refuses (permanent).
+ const msgSeq = new Map()
+ const lastMsgId = new Map()
+
+ const send = packet => { if (socket?.readyState === 1) socket.send(JSON.stringify(packet)) }
+ const heartbeat = () => send({ op: 1, d: sequence ?? null })
+ const scheduleHeartbeat = (interval) => {
+ clearTimeout(heartbeatTimer)
+ heartbeatAcked = true
+ const beat = () => {
+ if (!heartbeatAcked) { socket?.close(4000, 'Heartbeat lost'); return }
+ heartbeatAcked = false
+ heartbeat()
+ heartbeatTimer = setTimeout(beat, interval)
+ heartbeatTimer.unref?.()
+ }
+ heartbeatTimer = setTimeout(beat, interval)
+ heartbeatTimer.unref?.()
+ }
+
+ const refresh = () => {
+ const wait = Math.max(5_000, expiresAt - Date.now() - 60_000)
+ refreshTimer = setTimeout(async () => {
+ if (stopped) return
+ try {
+ const next = await getToken(fields, env)
+ token = next.token
+ expiresAt = next.expiresAt
+ } catch (error) {
+ env.log?.warn?.('ds-bot im: qq token refresh failed: %s', error?.message ?? error)
+ }
+ refresh()
+ }, wait)
+ refreshTimer.unref?.()
+ }
+
+ const onDispatch = async (packet) => {
+ if (packet.t === 'READY') {
+ sessionId = packet.d?.session_id
+ handlers.onStatus({ state: 'ready', account: { id: String(fields.appId).trim(), name: packet.d?.user?.username ? `@${packet.d.user.username}` : String(fields.appId).trim() } })
+ return
+ }
+ if (packet.t === 'RESUMED') { handlers.onStatus({ state: 'ready' }); return }
+ const c2c = packet.t === 'C2C_MESSAGE_CREATE'
+ const group = packet.t === 'GROUP_AT_MESSAGE_CREATE'
+ if (!c2c && !group) return
+ const d = packet.d ?? {}
+ const key = String(c2c ? d.author?.user_openid ?? d.channel_id ?? '' : d.group_openid ?? d.channel_id ?? '')
+ lastMsgId.set(key, String(d.id ?? ''))
+ const sender = c2c ? d.author?.user_openid : d.author?.member_openid ?? d.author?.id
+ await handlers.onMessage({
+ chat: { key, kind: c2c ? 'direct' : 'group', title: '' },
+ sender: { id: String(sender ?? ''), name: String(sender ?? '') },
+ text: String(d.content ?? '').trim(),
+ images: [], files: [],
+ mentioned: group, messageId: String(d.id ?? ''),
+ })
+ }
+
+ const open = (resume) => {
+ const gen = generation
+ try {
+ socket = new env.WebSocket(gatewayUrl)
+ } catch (error) {
+ handlers.onStatus({ state: 'error', error: `QQ could not open a socket: ${error?.message ?? error}` })
+ return
+ }
+ socket.addEventListener('message', (event) => {
+ if (stopped || generation !== gen) return
+ let packet
+ try { packet = JSON.parse(String(event.data)) } catch { return }
+ if (Number.isSafeInteger(packet.s)) sequence = packet.s
+ if (packet.op === 10) {
+ scheduleHeartbeat(Number(packet.d?.heartbeat_interval) || 40_000)
+ send(resume && sessionId
+ ? { op: 6, d: { token: `QQBot ${token}`, session_id: sessionId, seq: sequence ?? null } }
+ : { op: 2, d: { token: `QQBot ${token}`, intents: INTENTS, shard: [0, 1], properties: { os: process.platform, browser: 'ds-bot', device: 'ds-bot' } } })
+ return
+ }
+ if (packet.op === 11) { heartbeatAcked = true; return }
+ if (packet.op === 1) { heartbeat(); return }
+ if (packet.op === 7) { socket.close(4000, 'Reconnect requested'); return }
+ if (packet.op === 9) {
+ if (packet.d !== true) { sessionId = undefined; sequence = undefined }
+ socket.close(4000, 'Invalid session')
+ return
+ }
+ if (packet.op === 0) void onDispatch(packet).catch(error => env.log?.warn?.('ds-bot im: qq event failed: %s', error?.message ?? error))
+ })
+ socket.addEventListener('close', () => {
+ clearTimeout(heartbeatTimer)
+ if (stopped || generation !== gen) return
+ handlers.onStatus({ state: 'connecting' })
+ reconnectTimer = setTimeout(() => { if (!stopped) open(sessionId !== undefined) }, 2000)
+ reconnectTimer.unref?.()
+ })
+ socket.addEventListener('error', () => {})
+ }
+
+ let gatewayUrl
+ handlers.onStatus({ state: 'connecting' })
+ void (async () => {
+ try {
+ const got = await getToken(fields, env)
+ token = got.token
+ expiresAt = got.expiresAt
+ const gateway = await api(env, token, '/gateway', { method: 'GET' })
+ gatewayUrl = gateway?.url
+ } catch (error) {
+ handlers.onStatus({ state: 'error', error: error.message })
+ return
+ }
+ if (stopped) return
+ refresh()
+ open(false)
+ })()
+
+ return {
+ send: async (chat, { text }) => {
+ const chunks = chunkMarkdown(String(text ?? ''), TEXT_LIMIT)
+ const msgId = lastMsgId.get(chat.key)
+ const base = chat.kind === 'direct' ? `/v2/users/${chat.key}/messages` : `/v2/groups/${chat.key}/messages`
+ let messageId
+ for (const chunk of chunks) {
+ const seq = (msgSeq.get(msgId) ?? 0) + 1
+ msgSeq.set(msgId, seq)
+ const sent = await api(env, token, base, {
+ method: 'POST',
+ body: { content: chunk, msg_type: 0, ...(msgId ? { msg_id: msgId, msg_seq: seq } : {}) },
+ })
+ messageId = String(sent?.id ?? messageId ?? '')
+ }
+ return { messageId }
+ },
+ stop: () => {
+ stopped = true
+ generation += 1
+ clearTimeout(heartbeatTimer)
+ clearTimeout(reconnectTimer)
+ clearTimeout(refreshTimer)
+ try { socket?.close(1000, 'stop') } catch { /* not open */ }
+ },
+ }
+ },
+}
+
+async function api(env, token, path, { method = 'GET', body } = {}) {
+ const response = await env.fetch(`${apiBase(env)}${path}`, {
+ method,
+ headers: { authorization: `QQBot ${token}`, 'content-type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ })
+ const json = await response.json().catch(() => ({}))
+ if (!response.ok || json.code !== undefined) {
+ const reason = json.message ?? json.error ?? `QQ answered ${response.status}`
+ const error = new Error(String(reason))
+ error.status = response.status
+ // A refusal outside the reply window or over quota is permanent; 4xx other
+ // than auth problems too. 5xx and timeouts retry.
+ error.permanent = response.status >= 400 && response.status < 500 && response.status !== 429
+ || /reply.*window|quota|frequency|超过|过期/i.test(String(reason))
+ if (response.status === 429) error.retryAfter = Number(response.headers.get('retry-after'))
+ throw error
+ }
+ return json
+}
diff --git a/ds-bot/src/host/im/platforms/slack.js b/ds-bot/src/host/im/platforms/slack.js
new file mode 100644
index 00000000..cb87ddd1
--- /dev/null
+++ b/ds-bot/src/host/im/platforms/slack.js
@@ -0,0 +1,210 @@
+// Slack: Socket Mode over a WebSocket for inbound (xapp- token opens a
+// connection URL with apps.connections.open, every envelope must be ACKed,
+// disconnect frames mean reconnect), the Web API (xoxb- token) for sends and
+// edits. A message in an `im` channel is direct; `app_mention` is the group
+// trigger. Buttons are Block Kit actions; block_actions come back as
+// interactive envelopes. Wire details ported from dsh-im (MIT, see NOTICE).
+import { chunkMarkdown } from '../format.js'
+
+const API = 'https://slack.com/api/'
+const TEXT_LIMIT = 4000
+
+const apiBase = env => `${String(env.config?.api ?? API).replace(/\/+$/, '')}/`
+
+const fail = (reason) => {
+ const error = new Error(`Slack answered ${String(reason).replaceAll('_', ' ')}`)
+ error.permanent = !['rate_limited', 'fatal_error', 'internal_error'].includes(String(reason))
+ return error
+}
+
+const toMrkdwn = (markdown) => String(markdown ?? '')
+ // fenced code keeps its contents verbatim
+ .split(/(```[\s\S]*?```)/g)
+ .map((part, index) => index % 2 === 1 ? part : part
+ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<$2|$1>')
+ .replace(/\*\*([^*]+)\*\*/g, '*$1*')
+ .replace(/(^|\s)\*([^*\n]+)\*/g, '$1_$2_'))
+ .join('')
+
+export default {
+ id: 'slack',
+
+ async check(fields, env) {
+ const me = await call(env, fields, 'auth.test', {})
+ if (me?.user_id === undefined) throw new Error('These credentials do not belong to a Slack bot')
+ return { account: { id: String(me.user_id), name: me.user ? `@${me.user}` : String(me.user_id) } }
+ },
+
+ connect(fields, env, handlers) {
+ const appToken = String(fields.appToken ?? '').trim()
+ const botToken = String(fields.botToken ?? '').trim()
+ let stopped = false
+ let socket
+ let generation = 0
+ let reconnectTimer
+ let selfId = ''
+
+ const api = (method, params) => call(env, { botToken }, method, params)
+ const openUrl = async () => {
+ const response = await env.fetch(`${apiBase(env)}apps.connections.open`, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${appToken}` },
+ })
+ const body = await response.json().catch(() => ({}))
+ if (response.status === 429) throw Object.assign(new Error('Slack rate limited the connection'), { retryAfter: Number(response.headers.get('retry-after')) })
+ if (!body.ok) throw fail(body.error ?? `HTTP ${response.status}`)
+ return body.url
+ }
+
+ const onEvent = async (event) => {
+ // Bots and message subtypes (joins, edits) are not user messages.
+ if (event.bot_id !== undefined || (event.subtype !== undefined && event.subtype !== 'file_share')) return
+ const direct = event.type === 'message' && event.channel_type === 'im'
+ const mentioned = event.type === 'app_mention'
+ if (!direct && !mentioned) return
+ const images = []
+ const files = []
+ for (const file of event.files ?? []) {
+ const mediaType = String(file.mimetype ?? '')
+ const bytes = await download(file.url_private, botToken, env).catch(() => undefined)
+ if (bytes === undefined) continue
+ if (mediaType.startsWith('image/')) images.push({ mediaType, data: Buffer.from(bytes).toString('base64') })
+ else files.push({ name: String(file.name ?? 'file'), data: bytes })
+ }
+ const text = String(event.text ?? '').replaceAll(`<@${selfId}>`, '').trim()
+ await handlers.onMessage({
+ chat: { key: String(event.channel ?? ''), kind: direct ? 'direct' : 'group', title: '' },
+ sender: { id: String(event.user ?? ''), name: String(event.user ?? '') },
+ text, images, files, mentioned,
+ messageId: String(event.ts ?? ''),
+ })
+ }
+
+ const onInteractive = async (payload) => {
+ if (payload.type !== 'block_actions') return
+ const action = payload.actions?.[0]
+ if (action === undefined) return
+ await handlers.onAction({
+ chat: { key: String(payload.channel?.id ?? ''), kind: 'direct', title: '' },
+ sender: { id: String(payload.user?.id ?? ''), name: String(payload.user?.name ?? payload.user?.id ?? '') },
+ data: String(action.value ?? action.action_id ?? ''),
+ messageId: String(payload.message?.ts ?? ''),
+ })
+ }
+
+ const open = async () => {
+ const gen = generation
+ let url
+ try { url = await openUrl() } catch (error) {
+ if (!stopped) {
+ handlers.onStatus({ state: 'error', error: error.message })
+ if (error.retryAfter === undefined && error.permanent) return
+ reconnectTimer = setTimeout(() => { if (!stopped) void open() }, (error.retryAfter ?? 5) * 1000)
+ reconnectTimer.unref?.()
+ }
+ return
+ }
+ try { socket = new env.WebSocket(url) } catch (error) {
+ handlers.onStatus({ state: 'error', error: `Slack could not open a socket: ${error?.message ?? error}` })
+ return
+ }
+ socket.addEventListener('message', (event) => {
+ if (stopped || generation !== gen) return
+ let packet
+ try { packet = JSON.parse(String(event.data)) } catch { return }
+ if (packet.type === 'hello') {
+ handlers.onStatus({ state: 'ready' })
+ return
+ }
+ // Every envelope is ACKed by echoing its id.
+ if (packet.envelope_id !== undefined && socket?.readyState === 1) {
+ try { socket.send(JSON.stringify({ envelope_id: packet.envelope_id })) } catch { /* closing */ }
+ }
+ if (packet.type === 'disconnect') { socket.close(4000); return }
+ if (packet.type === 'events_api' && packet.payload?.type === 'event_callback') {
+ void onEvent(packet.payload.event ?? {}).catch(error => env.log?.warn?.('ds-bot im: slack event failed: %s', error?.message ?? error))
+ } else if (packet.type === 'interactive') {
+ void onInteractive(packet.payload ?? {}).catch(error => env.log?.warn?.('ds-bot im: slack action failed: %s', error?.message ?? error))
+ }
+ })
+ socket.addEventListener('close', () => {
+ if (stopped || generation !== gen) return
+ handlers.onStatus({ state: 'connecting' })
+ reconnectTimer = setTimeout(() => { if (!stopped) void open() }, 2000)
+ reconnectTimer.unref?.()
+ })
+ socket.addEventListener('error', () => {})
+ }
+
+ handlers.onStatus({ state: 'connecting' })
+ void (async () => {
+ try {
+ const me = await api('auth.test', {})
+ selfId = String(me?.user_id ?? '')
+ } catch { /* the socket still tells us what it is */ }
+ if (!stopped) await open()
+ })()
+
+ const blocksFor = (text, buttons) => {
+ const blocks = [{ type: 'section', text: { type: 'mrkdwn', text } }]
+ if (buttons?.length > 0) {
+ blocks.push({
+ type: 'actions',
+ elements: buttons.slice(0, 5).map((button, index) => ({
+ type: 'button',
+ action_id: `b${index}`,
+ text: { type: 'plain_text', text: button.label.slice(0, 75) },
+ value: button.data,
+ })),
+ })
+ }
+ return blocks
+ }
+
+ return {
+ send: async (chat, { text, buttons }) => {
+ const chunks = chunkMarkdown(text, TEXT_LIMIT)
+ let messageId
+ for (const [index, chunk] of chunks.entries()) {
+ const result = await api('chat.postMessage', {
+ channel: chat.key,
+ text: chunk,
+ blocks: blocksFor(toMrkdwn(chunk), index === chunks.length - 1 ? buttons : undefined),
+ })
+ messageId = String(result?.ts ?? messageId ?? '')
+ }
+ return { messageId }
+ },
+ edit: async (chat, messageId, { text, buttons }) => {
+ await api('chat.update', { channel: chat.key, ts: messageId, text: toMrkdwn(text).slice(0, TEXT_LIMIT), blocks: blocksFor(toMrkdwn(text).slice(0, TEXT_LIMIT), buttons) })
+ },
+ stop: () => {
+ stopped = true
+ generation += 1
+ clearTimeout(reconnectTimer)
+ try { socket?.close(1000) } catch { /* not open */ }
+ },
+ }
+ },
+}
+
+async function call(env, fields, method, params) {
+ const response = await env.fetch(`${apiBase(env)}${method}`, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${String(fields.botToken ?? fields.appToken ?? '').trim()}`,
+ 'content-type': 'application/json; charset=utf-8',
+ },
+ body: JSON.stringify(params),
+ })
+ const body = await response.json().catch(() => ({}))
+ if (response.status === 429) throw Object.assign(new Error('Slack rate limited the send'), { retryAfter: Number(response.headers.get('retry-after')) })
+ if (!body.ok) throw fail(body.error ?? `HTTP ${response.status}`)
+ return body
+}
+
+async function download(url, token, env) {
+ const response = await env.fetch(String(url ?? ''), { headers: { authorization: `Bearer ${token}` } })
+ if (!response.ok) return undefined
+ return new Uint8Array(await response.arrayBuffer())
+}
diff --git a/ds-bot/test/im-qq.test.js b/ds-bot/test/im-qq.test.js
new file mode 100644
index 00000000..c9aed010
--- /dev/null
+++ b/ds-bot/test/im-qq.test.js
@@ -0,0 +1,136 @@
+import assert from 'node:assert/strict'
+import { createServer } from 'node:http'
+import { test } from 'node:test'
+import qq from '../src/host/im/platforms/qq.js'
+import { fakeWsServer } from './fake-ws.js'
+
+// A fake QQ open platform: /app/getAppAccessToken issues a token, /gateway the
+// fake socket URL, C2C and group @ events come from the test, and sends record
+// their msg_id/msg_seq.
+async function fakeQq() {
+ const calls = []
+ const replies = {}
+ const packets = []
+ const http = createServer((req, res) => {
+ let body = ''
+ req.on('data', chunk => { body += chunk })
+ req.on('end', () => {
+ const params = JSON.parse(body || '{}')
+ const call = { method: req.method, path: req.url, params, auth: req.headers.authorization }
+ calls.push(call)
+ let answer = replies[req.url]
+ if (answer === undefined && req.url === '/app/getAppAccessToken') answer = { result: { access_token: 'qqtok', expires_in: 7200 } }
+ if (answer === undefined && req.url === '/gateway') answer = { result: { url: wss.url } }
+ if (typeof answer === 'function') answer = answer(params)
+ if (answer === undefined) answer = { result: { id: '900' } }
+ if (answer.error) {
+ res.writeHead(answer.status ?? 400, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ code: answer.error, message: answer.message ?? 'refused' }))
+ return
+ }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify(answer.result))
+ })
+ })
+ const wss = await fakeWsServer({
+ onSocket(ws) {
+ ws.on('message', (raw) => {
+ const packet = JSON.parse(raw)
+ packets.push(packet)
+ if (packet.op === 2) ws.send(JSON.stringify({ op: 0, t: 'READY', s: 1, d: { session_id: 's1', user: { id: '81', username: 'fakebot' } } }))
+ if (packet.op === 6) ws.send(JSON.stringify({ op: 0, t: 'RESUMED', s: 9, d: {} }))
+ if (packet.op === 1) ws.send(JSON.stringify({ op: 11, d: null }))
+ })
+ ws.send(JSON.stringify({ op: 10, d: { heartbeat_interval: 30_000 } }))
+ },
+ })
+ await new Promise(resolve => http.listen(0, '127.0.0.1', resolve))
+ return {
+ api: `http://127.0.0.1:${http.address().port}`,
+ calls, replies, packets,
+ sockets: wss.sockets,
+ push: (ws, packet) => ws.send(JSON.stringify(packet)),
+ close: () => { wss.close(); http.closeAllConnections?.(); http.close() },
+ }
+}
+
+const env = (fake, runtime = {}) => ({
+ fetch: globalThis.fetch,
+ WebSocket: globalThis.WebSocket,
+ config: { api: fake.api, token: fake.api },
+ runtime: { get: () => runtime, set: patch => Object.assign(runtime, patch) },
+ log: { warn: (...args) => console.error('[im-qq]', ...args) },
+})
+const FIELDS = { appId: '1020', appSecret: 'sekret' }
+
+const until = async (fn, tries = 80) => {
+ for (let at = 0; at < tries; at += 1) {
+ const value = await fn()
+ if (value !== undefined && value !== false) return value
+ await new Promise(done => setTimeout(done, 50))
+ }
+ return undefined
+}
+
+test('check gets an app access token and names the account', async () => {
+ const fake = await fakeQq()
+ const { account } = await qq.check(FIELDS, env(fake))
+ assert.equal(account.id, '1020')
+ const token = fake.calls.find(call => call.path === '/app/getAppAccessToken')
+ assert.equal(token.params.appId, '1020')
+ assert.equal(token.params.clientSecret, 'sekret')
+ await fake.close()
+})
+
+test('C2C is direct, a group @ is a mention, heartbeats are answered', async (t) => {
+ const fake = await fakeQq()
+ const messages = []
+ const handle = qq.connect(FIELDS, env(fake), { onMessage: async msg => { messages.push(msg) }, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ await until(() => fake.packets.some(packet => packet.op === 2))
+ fake.push(ws, { op: 0, t: 'C2C_MESSAGE_CREATE', s: 2, d: { id: 'm1', content: 'hello', author: { user_openid: 'u1' } } })
+ fake.push(ws, { op: 0, t: 'GROUP_AT_MESSAGE_CREATE', s: 3, d: { id: 'm2', content: 'ping', group_openid: 'g1', author: { member_openid: 'u2' } } })
+ await until(() => messages.length === 2)
+ assert.equal(messages[0].chat.kind, 'direct')
+ assert.equal(messages[0].chat.key, 'u1')
+ assert.equal(messages[1].chat.kind, 'group')
+ assert.equal(messages[1].chat.key, 'g1')
+ assert.equal(messages[1].mentioned, true)
+ // A heartbeat request from the server gets an op-1 reply.
+ fake.push(ws, { op: 1, d: null })
+ await until(() => fake.packets.filter(packet => packet.op === 1).length === 2)
+})
+
+test('send replies passively with msg_id and a climbing msg_seq; a refusal is permanent', async (t) => {
+ const fake = await fakeQq()
+ const messages = []
+ const handle = qq.connect(FIELDS, env(fake), { onMessage: async msg => { messages.push(msg) }, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ await until(() => fake.packets.some(packet => packet.op === 2))
+ fake.push(ws, { op: 0, t: 'C2C_MESSAGE_CREATE', s: 2, d: { id: 'm1', content: 'hi', author: { user_openid: 'u1' } } })
+ await until(() => messages.length === 1)
+ await handle.send({ key: 'u1', kind: 'direct' }, { text: 'one' })
+ await handle.send({ key: 'u1', kind: 'direct' }, { text: 'two' })
+ const posts = fake.calls.filter(call => call.path === '/v2/users/u1/messages')
+ assert.equal(posts.length, 2)
+ assert.equal(posts[0].params.msg_id, 'm1')
+ assert.equal(posts[0].params.msg_seq, 1)
+ assert.equal(posts[1].params.msg_seq, 2)
+ // A refusal outside the reply window is a permanent error with the reason.
+ fake.replies['/v2/users/u1/messages'] = { error: 304023, message: 'reply time out' }
+ await assert.rejects(() => handle.send({ key: 'u1', kind: 'direct' }, { text: 'late' }), error => error.permanent === true && /reply/.test(error.message))
+})
+
+test('a dropped socket reconnects and resumes', async (t) => {
+ const fake = await fakeQq()
+ const statuses = []
+ const handle = qq.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: () => {}, onStatus: status => statuses.push(status) })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ await until(() => statuses.some(status => status.state === 'ready'))
+ ws.close()
+ await until(() => fake.sockets.length === 2)
+ await until(() => fake.packets.some(packet => packet.op === 6))
+})
diff --git a/ds-bot/test/im-slack.test.js b/ds-bot/test/im-slack.test.js
new file mode 100644
index 00000000..c0840126
--- /dev/null
+++ b/ds-bot/test/im-slack.test.js
@@ -0,0 +1,146 @@
+import assert from 'node:assert/strict'
+import { createServer } from 'node:http'
+import { test } from 'node:test'
+import slack from '../src/host/im/platforms/slack.js'
+import { fakeWsServer } from './fake-ws.js'
+
+// A fake Slack: the Web API answers from `replies`, apps.connections.open hands
+// back the fake Socket Mode URL; envelopes pushed by the test must be ACKed.
+async function fakeSlack() {
+ const calls = []
+ const replies = {}
+ const packets = []
+ const acks = []
+ const http = createServer((req, res) => {
+ let body = ''
+ req.on('data', chunk => { body += chunk })
+ req.on('end', () => {
+ const method = req.url.slice(1)
+ const params = JSON.parse(body || '{}')
+ calls.push({ method, params, auth: req.headers.authorization })
+ let answer = replies[method]
+ if (answer === undefined && method === 'auth.test') answer = { result: { ok: true, user_id: 'U81', user: 'fakebot' } }
+ if (answer === undefined && method === 'apps.connections.open') answer = { result: { ok: true, url: wss.url } }
+ if (typeof answer === 'function') answer = answer(params)
+ if (answer === undefined) answer = { result: { ok: true, ts: '1700.1' } }
+ if (answer.error) {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ ok: false, error: answer.error }))
+ return
+ }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify(answer.result))
+ })
+ })
+ const wss = await fakeWsServer({
+ onSocket(ws) {
+ ws.on('message', (raw) => {
+ const packet = JSON.parse(raw)
+ packets.push(packet)
+ if (packet.envelope_id !== undefined) acks.push(packet.envelope_id)
+ })
+ ws.send(JSON.stringify({ type: 'hello' }))
+ },
+ })
+ await new Promise(resolve => http.listen(0, '127.0.0.1', resolve))
+ return {
+ api: `http://127.0.0.1:${http.address().port}`,
+ calls, replies, packets, acks,
+ sockets: wss.sockets,
+ push: (ws, packet) => ws.send(JSON.stringify(packet)),
+ close: () => { wss.close(); http.closeAllConnections?.(); http.close() },
+ }
+}
+
+const env = (fake, runtime = {}) => ({
+ fetch: globalThis.fetch,
+ WebSocket: globalThis.WebSocket,
+ config: { api: fake.api },
+ runtime: { get: () => runtime, set: patch => Object.assign(runtime, patch) },
+ log: { warn: (...args) => console.error('[im-slack]', ...args) },
+})
+const FIELDS = { appToken: 'xapp-a', botToken: 'xoxb-b' }
+
+const until = async (fn, tries = 80) => {
+ for (let at = 0; at < tries; at += 1) {
+ const value = await fn()
+ if (value !== undefined && value !== false) return value
+ await new Promise(done => setTimeout(done, 50))
+ }
+ return undefined
+}
+
+const envelope = (payload) => ({ envelope_id: `e${Math.random()}`, type: 'events_api', payload: { type: 'event_callback', event: payload } })
+
+test('check validates the bot token with auth.test', async () => {
+ const fake = await fakeSlack()
+ const { account } = await slack.check(FIELDS, env(fake))
+ assert.deepEqual(account, { id: 'U81', name: '@fakebot' })
+ assert.ok(fake.calls.some(call => call.method === 'auth.test' && call.auth === 'Bearer xoxb-b'))
+ await fake.close()
+})
+
+test('a message in an im channel is direct, app_mention is group, every envelope is ACKed', async (t) => {
+ const fake = await fakeSlack()
+ const messages = []
+ const handle = slack.connect(FIELDS, env(fake), { onMessage: async msg => { messages.push(msg) }, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ await until(() => fake.calls.some(call => call.method === 'apps.connections.open' && call.auth === 'Bearer xapp-a'))
+ fake.push(ws, envelope({ type: 'message', channel_type: 'im', channel: 'D1', user: 'U2', text: 'hello', ts: '1.0' }))
+ fake.push(ws, envelope({ type: 'app_mention', channel: 'C1', user: 'U3', text: '<@U81> ping', ts: '2.0' }))
+ fake.push(ws, envelope({ type: 'message', channel_type: 'channel', channel: 'C1', user: 'U3', text: 'noise', ts: '3.0' }))
+ fake.push(ws, envelope({ type: 'message', channel_type: 'im', channel: 'D1', user: 'U2', text: 'bot echo', bot_id: 'B1', ts: '4.0' }))
+ await until(() => messages.length === 2)
+ assert.equal(messages[0].chat.kind, 'direct')
+ assert.equal(messages[1].chat.kind, 'group')
+ assert.equal(messages[1].mentioned, true)
+ assert.equal(messages[1].text, 'ping')
+ await until(() => fake.acks.length === 4)
+})
+
+test('a block_actions envelope reports the action', async (t) => {
+ const fake = await fakeSlack()
+ const actions = []
+ const handle = slack.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: async action => { actions.push(action) }, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ await until(() => fake.sockets.length === 1)
+ fake.push(ws, {
+ envelope_id: 'ev1', type: 'interactive',
+ payload: { type: 'block_actions', channel: { id: 'D1' }, user: { id: 'U2', name: 'Fei' }, actions: [{ action_id: 'b0', value: 'q:q1:0' }], message: { ts: '9.9' } },
+ })
+ await until(() => actions.length === 1)
+ assert.equal(actions[0].data, 'q:q1:0')
+ assert.equal(actions[0].messageId, '9.9')
+})
+
+test('send posts blocks with buttons, edit calls chat.update', async (t) => {
+ const fake = await fakeSlack()
+ const handle = slack.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ await until(() => fake.sockets[0])
+ const { messageId } = await handle.send({ key: 'D1', kind: 'direct' }, { text: 'hello', buttons: [{ data: 'q:q1:0', label: 'yes' }, { data: 'q:q1:1', label: 'no' }] })
+ const post = fake.calls.find(call => call.method === 'chat.postMessage')
+ assert.ok(post, 'chat.postMessage called')
+ assert.equal(post.params.channel, 'D1')
+ const buttons = post.params.blocks.at(-1).elements
+ assert.equal(buttons.length, 2)
+ assert.equal(buttons[0].value, 'q:q1:0')
+ assert.equal(messageId, '1700.1')
+ await handle.edit({ key: 'D1', kind: 'direct' }, '9.9', { text: 'done', buttons: [] })
+ const update = fake.calls.find(call => call.method === 'chat.update')
+ assert.ok(update, 'chat.update called')
+ assert.equal(update.params.ts, '9.9')
+})
+
+test('a disconnect frame and a dropped socket both reconnect', async (t) => {
+ const fake = await fakeSlack()
+ const statuses = []
+ const handle = slack.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: () => {}, onStatus: status => statuses.push(status) })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ fake.push(ws, { type: 'disconnect', reason: 'link_disabled' })
+ await until(() => fake.sockets.length === 2)
+ assert.ok(statuses.some(status => status.state === 'ready'))
+})