mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-09 04:13:17 +08:00
feat: add Slack bot integration
This commit is contained in:
parent
bee4c2927f
commit
7d44861a07
28 changed files with 3021 additions and 661 deletions
|
|
@ -106,6 +106,19 @@ export function DiscordLogoGlyph({ size } = {}) {
|
|||
}));
|
||||
}
|
||||
|
||||
export function SlackLogoGlyph({ size } = {}) {
|
||||
return h('svg', {
|
||||
...dimensions(size),
|
||||
viewBox: '0 0 24 24',
|
||||
focusable: 'false',
|
||||
'aria-hidden': 'true',
|
||||
'data-im-channel-logo': 'slack',
|
||||
}, h('path', {
|
||||
fill: 'currentColor',
|
||||
d: 'M6 15a2 2 0 1 1-2-2h2v2Zm1 0a2 2 0 1 1 4 0v5a2 2 0 1 1-4 0v-5Zm2-8a2 2 0 1 1 2-2v2H9Zm0 1a2 2 0 1 1 0 4H4a2 2 0 1 1 0-4h5Zm8 2a2 2 0 1 1 2 2h-2v-2Zm-1 0a2 2 0 1 1-4 0V5a2 2 0 1 1 4 0v5Zm-2 8a2 2 0 1 1-2 2v-2h2Zm0-1a2 2 0 1 1 0-4h5a2 2 0 1 1 0 4h-5Z',
|
||||
}));
|
||||
}
|
||||
|
||||
export function WhatsappLogoGlyph({ size } = {}) {
|
||||
return h('svg', {
|
||||
...dimensions(size),
|
||||
|
|
|
|||
11
plugin-src/client/channels/slack/api.js
Normal file
11
plugin-src/client/channels/slack/api.js
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { TOKEN_BOT_ENDPOINTS, createTokenChannelApi } from '../shared/token-api.js';
|
||||
|
||||
export const SLACK_RPC_CHANNEL = '/slack';
|
||||
export const SLACK_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
|
||||
|
||||
const api = createTokenChannelApi('Slack', ' Socket Mode 长连接');
|
||||
|
||||
export const unwrapRpcResult = api.unwrapRpcResult;
|
||||
export const normalizeSnapshot = api.normalizeSnapshot;
|
||||
export const presentError = api.presentError;
|
||||
export { api as slackClientApi };
|
||||
131
plugin-src/client/channels/slack/index.js
Normal file
131
plugin-src/client/channels/slack/index.js
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import * as React from 'react';
|
||||
|
||||
import { SlackLogoGlyph } from '../../channel-logos.js';
|
||||
import { createTokenChannelSettings } from '../shared/token-channel.js';
|
||||
import {
|
||||
SLACK_CREATE_APP_URL,
|
||||
SLACK_APP_MANIFEST_YAML,
|
||||
} from '../../../../src/channels/slack/manifest.mjs';
|
||||
import { SLACK_ENDPOINTS, slackClientApi } from './api.js';
|
||||
import { installSlackStyles } from './styles.js';
|
||||
|
||||
const h = React.createElement;
|
||||
|
||||
export function SlackCredentialPanel({ busy, error, onSubmit, onCancel }) {
|
||||
const [botToken, setBotToken] = React.useState('');
|
||||
const [appToken, setAppToken] = React.useState('');
|
||||
const [copied, setCopied] = React.useState(false);
|
||||
const headingId = React.useId();
|
||||
|
||||
const copyManifest = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(SLACK_APP_MANIFEST_YAML);
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 2_000);
|
||||
} catch {
|
||||
setCopied(false);
|
||||
}
|
||||
};
|
||||
|
||||
const submit = (event) => {
|
||||
event.preventDefault();
|
||||
const normalizedBotToken = botToken.trim();
|
||||
const normalizedAppToken = appToken.trim();
|
||||
if (!normalizedBotToken || !normalizedAppToken || busy) return;
|
||||
void onSubmit?.({ botToken: normalizedBotToken, appToken: normalizedAppToken });
|
||||
};
|
||||
|
||||
return h('section', {
|
||||
className: 'ddt-card dim-surfaceCard dim-credentialPanel dsl-setup',
|
||||
'aria-labelledby': headingId,
|
||||
},
|
||||
h('h3', { id: headingId, className: 'dim-credentialTitle' }, '接入 Slack 机器人'),
|
||||
h('div', { className: 'dsl-guide' },
|
||||
h('div', { className: 'dsl-guideCopy' },
|
||||
h('strong', null, '先用 Manifest 创建并配置 Slack App'),
|
||||
h('p', null, '复制配置后,在 Slack 选择 From a manifest;创建完成后生成 connections:write App Token,并将应用安装到工作区。')),
|
||||
h('div', { className: 'dsl-guideActions' },
|
||||
h('button', {
|
||||
type: 'button',
|
||||
className: 'ddt-button',
|
||||
onClick: () => void copyManifest(),
|
||||
disabled: busy,
|
||||
}, copied ? h('span', { className: 'dsl-copyState' }, '已复制 Manifest') : '复制 Manifest'),
|
||||
h('a', {
|
||||
className: 'ddt-button',
|
||||
href: SLACK_CREATE_APP_URL,
|
||||
target: '_blank',
|
||||
rel: 'noreferrer',
|
||||
}, '打开 Slack 创建页'))),
|
||||
h('form', { className: 'dim-credentialForm dim-credentialFormSingle', onSubmit: submit },
|
||||
h('div', { className: 'dsl-fields' },
|
||||
h('label', { className: 'dim-credentialField' },
|
||||
h('span', null, 'Bot Token'),
|
||||
h('input', {
|
||||
type: 'password',
|
||||
value: botToken,
|
||||
onChange: (event) => setBotToken(event.target.value),
|
||||
placeholder: 'xoxb-…',
|
||||
maxLength: 4096,
|
||||
autoCapitalize: 'none',
|
||||
autoCorrect: 'off',
|
||||
spellCheck: false,
|
||||
autoComplete: 'new-password',
|
||||
disabled: busy,
|
||||
required: true,
|
||||
})),
|
||||
h('label', { className: 'dim-credentialField' },
|
||||
h('span', null, 'App Token'),
|
||||
h('input', {
|
||||
type: 'password',
|
||||
value: appToken,
|
||||
onChange: (event) => setAppToken(event.target.value),
|
||||
placeholder: 'xapp-…',
|
||||
maxLength: 4096,
|
||||
autoCapitalize: 'none',
|
||||
autoCorrect: 'off',
|
||||
spellCheck: false,
|
||||
autoComplete: 'new-password',
|
||||
disabled: busy,
|
||||
required: true,
|
||||
})),
|
||||
h('p', { className: 'dsl-tokenHint' }, 'Bot Token 来自 OAuth & Permissions;App Token 来自 Basic Information,并且必须包含 connections:write。')),
|
||||
error ? h('p', { className: 'dim-credentialError', role: 'alert' }, error.message ?? String(error)) : null,
|
||||
h('div', { className: 'ddt-actions dim-viewActions dim-credentialActions' },
|
||||
h('button', {
|
||||
type: 'submit',
|
||||
className: 'ddt-button',
|
||||
'data-kind': 'primary',
|
||||
disabled: busy || !botToken.trim() || !appToken.trim(),
|
||||
}, busy ? '正在验证并连接…' : '验证并连接'),
|
||||
h('button', {
|
||||
type: 'button',
|
||||
className: 'ddt-button',
|
||||
onClick: onCancel,
|
||||
disabled: busy,
|
||||
}, '取消'))));
|
||||
}
|
||||
|
||||
const channel = createTokenChannelSettings({
|
||||
channel: 'Slack',
|
||||
endpoints: SLACK_ENDPOINTS,
|
||||
api: slackClientApi,
|
||||
LogoGlyph: SlackLogoGlyph,
|
||||
installStyles: installSlackStyles,
|
||||
pageClass: 'dsl-page',
|
||||
avatarClass: 'dsl-avatar',
|
||||
connectionLabel: 'Socket Mode 长连接',
|
||||
emptyTitle: '接入 Slack 机器人',
|
||||
emptyDescription: '使用官方 App Manifest 快速配置机器人,再填写 Bot Token 与 App Token 建立本地 Socket Mode 连接。',
|
||||
platformLabel: 'Slack 工作区',
|
||||
CredentialPanel: SlackCredentialPanel,
|
||||
credentialPayload: ({ botToken, appToken }) => ({ botToken, appToken }),
|
||||
credentialAriaLabel: '使用 Manifest 和双 Token 接入 Slack 机器人',
|
||||
credentialOpenLabel: '接入机器人',
|
||||
credentialCloseLabel: '收起接入',
|
||||
credentialNoun: 'Bot Token 与 App Token',
|
||||
emptyActionLabel: '开始接入',
|
||||
});
|
||||
|
||||
export const SlackSettingsTab = channel.SettingsTab;
|
||||
export const SlackAccountCard = channel.AccountCard;
|
||||
34
plugin-src/client/channels/slack/styles.js
Normal file
34
plugin-src/client/channels/slack/styles.js
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
export const SLACK_STYLE_ID = 'xmanrui-dsh-im-slack-settings';
|
||||
|
||||
const CSS = String.raw`
|
||||
.dsl-page { --ddt-accent: #4a154b; --ddt-accent-deep: #321033; --ddt-accent-wash: #f7eef7; }
|
||||
.dsl-avatar { color: #fff; background: #4a154b; }
|
||||
.dsl-avatar svg { display: block; }
|
||||
.dsl-setup { display: grid; gap: 18px; }
|
||||
.dsl-guide { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: start; gap: 18px; padding: 16px; border: 1px solid color-mix(in srgb, #4a154b 18%, var(--dsw-alias-border-l2, #e5e6eb)); border-radius: 11px; background: color-mix(in srgb, #4a154b 4%, var(--dsw-alias-bg-layer-1, #fff)); }
|
||||
.dsl-guideCopy { min-width: 0; }
|
||||
.dsl-guideCopy strong { display: block; margin-bottom: 5px; color: var(--dsw-alias-label-primary, #1f2329); font-size: 13px; }
|
||||
.dsl-guideCopy p { margin: 0; color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; line-height: 1.6; }
|
||||
.dsl-guideActions { display: flex; align-items: center; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
|
||||
.dsl-guideActions .ddt-button { white-space: nowrap; }
|
||||
.dsl-copyState { color: var(--dsw-alias-state-success-primary, #20a162); }
|
||||
.dsl-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||
.dsl-tokenHint { grid-column: 1 / -1; margin: -4px 0 0; color: var(--dsw-alias-label-tertiary, #8f959e); font-size: 11px; line-height: 1.55; }
|
||||
@container (max-width: 680px) {
|
||||
.dsl-guide { grid-template-columns: minmax(0, 1fr); }
|
||||
.dsl-guideActions { justify-content: flex-start; }
|
||||
.dsl-fields { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
`;
|
||||
|
||||
export function installSlackStyles() {
|
||||
if (typeof document === 'undefined') return () => {};
|
||||
const existing = document.querySelector(`style[data-plugin-css="${SLACK_STYLE_ID}"]`);
|
||||
if (existing) return () => {};
|
||||
const style = document.createElement('style');
|
||||
style.dataset.plugin = '@xmanrui/dsh-im';
|
||||
style.dataset.pluginCss = SLACK_STYLE_ID;
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
return () => style.remove();
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import {
|
|||
DiscordLogoGlyph,
|
||||
FeishuLogoGlyph,
|
||||
QqLogoGlyph,
|
||||
SlackLogoGlyph,
|
||||
TelegramLogoGlyph,
|
||||
WecomLogoGlyph,
|
||||
WeixinLogoGlyph,
|
||||
|
|
@ -21,6 +22,9 @@ import { installFeishuStyles } from './channels/feishu/styles.js';
|
|||
import { QQ_RPC_CHANNEL } from './channels/qq/api.js';
|
||||
import { QqSettingsTab } from './channels/qq/index.js';
|
||||
import { installQqStyles } from './channels/qq/styles.js';
|
||||
import { SLACK_RPC_CHANNEL } from './channels/slack/api.js';
|
||||
import { SlackSettingsTab } from './channels/slack/index.js';
|
||||
import { installSlackStyles } from './channels/slack/styles.js';
|
||||
import { TELEGRAM_RPC_CHANNEL } from './channels/telegram/api.js';
|
||||
import { TelegramSettingsTab } from './channels/telegram/index.js';
|
||||
import { installTelegramStyles } from './channels/telegram/styles.js';
|
||||
|
|
@ -46,6 +50,7 @@ const CHANNELS = Object.freeze([
|
|||
{ id: 'dingtalk', label: '钉钉' },
|
||||
{ id: 'wecom', label: '企业微信' },
|
||||
{ id: 'qq', label: 'QQ' },
|
||||
{ id: 'slack', label: 'Slack' },
|
||||
{ id: 'telegram', label: 'Telegram' },
|
||||
{ id: 'discord', label: 'Discord' },
|
||||
{ id: 'whatsapp', label: 'WhatsApp' },
|
||||
|
|
@ -79,6 +84,11 @@ function TelegramLogo() {
|
|||
h(TelegramLogoGlyph));
|
||||
}
|
||||
|
||||
function SlackLogo() {
|
||||
return h('span', { className: 'dim-logo dim-logoSlack', 'aria-hidden': 'true' },
|
||||
h(SlackLogoGlyph));
|
||||
}
|
||||
|
||||
function DiscordLogo() {
|
||||
return h('span', { className: 'dim-logo dim-logoDiscord', 'aria-hidden': 'true' },
|
||||
h(DiscordLogoGlyph));
|
||||
|
|
@ -95,6 +105,7 @@ function ChannelLogo({ channel }) {
|
|||
if (channel === 'dingtalk') return h(DingtalkLogo);
|
||||
if (channel === 'wecom') return h(WecomLogo);
|
||||
if (channel === 'qq') return h(QqLogo);
|
||||
if (channel === 'slack') return h(SlackLogo);
|
||||
if (channel === 'telegram') return h(TelegramLogo);
|
||||
if (channel === 'discord') return h(DiscordLogo);
|
||||
return h(WhatsappLogo);
|
||||
|
|
@ -105,6 +116,7 @@ export function IMSettingsTab({
|
|||
discordRpcCall,
|
||||
feishuRpcCall,
|
||||
qqRpcCall,
|
||||
slackRpcCall,
|
||||
telegramRpcCall,
|
||||
wecomRpcCall,
|
||||
weixinRpcCall,
|
||||
|
|
@ -148,6 +160,8 @@ export function IMSettingsTab({
|
|||
? h(WecomSettingsTab, { rpcCall: wecomRpcCall })
|
||||
: active.id === 'qq'
|
||||
? h(QqSettingsTab, { rpcCall: qqRpcCall })
|
||||
: active.id === 'slack'
|
||||
? h(SlackSettingsTab, { rpcCall: slackRpcCall })
|
||||
: active.id === 'telegram'
|
||||
? h(TelegramSettingsTab, { rpcCall: telegramRpcCall })
|
||||
: active.id === 'discord'
|
||||
|
|
@ -164,6 +178,7 @@ export function apply(ctx) {
|
|||
installWeixinStyles(),
|
||||
installWecomStyles(),
|
||||
installQqStyles(),
|
||||
installSlackStyles(),
|
||||
installTelegramStyles(),
|
||||
installDiscordStyles(),
|
||||
installWhatsappStyles(),
|
||||
|
|
@ -190,6 +205,8 @@ export function apply(ctx) {
|
|||
ctx.connection.rpc.call(DISCORD_RPC_CHANNEL, endpoint, payload, signal);
|
||||
const whatsappRpcCall = (endpoint, payload, signal) =>
|
||||
ctx.connection.rpc.call(WHATSAPP_RPC_CHANNEL, endpoint, payload, signal);
|
||||
const slackRpcCall = (endpoint, payload, signal) =>
|
||||
ctx.connection.rpc.call(SLACK_RPC_CHANNEL, endpoint, payload, signal);
|
||||
|
||||
ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
|
||||
name: 'settings.plugins.tab',
|
||||
|
|
@ -201,6 +218,7 @@ export function apply(ctx) {
|
|||
discordRpcCall,
|
||||
feishuRpcCall,
|
||||
qqRpcCall,
|
||||
slackRpcCall,
|
||||
telegramRpcCall,
|
||||
wecomRpcCall,
|
||||
weixinRpcCall,
|
||||
|
|
|
|||
|
|
@ -37,13 +37,15 @@ const CSS = String.raw`
|
|||
.dim-logoTelegram svg { width: 21px; height: 21px; }
|
||||
.dim-logoDiscord { color: white; background: #5865f2; }
|
||||
.dim-logoDiscord svg { width: 21px; height: 21px; }
|
||||
.dim-logoSlack { color: white; background: #4a154b; }
|
||||
.dim-logoSlack svg { width: 21px; height: 21px; }
|
||||
.dim-logoWhatsapp { color: white; background: #25d366; }
|
||||
.dim-logoWhatsapp svg { width: 21px; height: 21px; }
|
||||
.dim-channelCopy { min-width: 0; display: block; }
|
||||
.dim-channelCopy strong { overflow: hidden; color: inherit; font-size: 14px; line-height: 20px; font-weight: 680; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.dim-divider { width: 1px; min-height: 520px; background: var(--dsw-alias-border-l1, #eef0f3); }
|
||||
.dim-panel { min-width: 0; container-type: inline-size; }
|
||||
.dim-panel .bxf-page, .dim-panel .dxw-page, .dim-panel .ddt-page, .dim-panel .dqq-page, .dim-panel .dwecom-page, .dim-panel .dwa-page { width: 100%; max-width: none; padding: 0 0 24px; }
|
||||
.dim-panel .bxf-page, .dim-panel .dxw-page, .dim-panel .ddt-page, .dim-panel .dqq-page, .dim-panel .dwecom-page, .dim-panel .dsl-page, .dim-panel .dwa-page { width: 100%; max-width: none; padding: 0 0 24px; }
|
||||
.dim-panel .bxf-heading, .dim-panel .dxw-heading, .dim-panel .ddt-heading { justify-content: flex-end; }
|
||||
.dim-panel .bxf-headingTools, .dim-panel .dxw-tools, .dim-panel .ddt-tools { width: 100%; justify-content: space-between; }
|
||||
.dim-panel .dim-bindActions { min-width: 0; display: flex; align-items: center; flex-wrap: nowrap; gap: 8px; }
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { join, resolve } from 'node:path';
|
|||
|
||||
import { createTokenConnectionSupervisor } from './connection-supervisor.mjs';
|
||||
|
||||
function harnessOrigin(webServer, configured) {
|
||||
export function harnessOrigin(webServer, configured) {
|
||||
if (configured !== undefined) return new URL(configured);
|
||||
const port = webServer?.port;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
|
||||
|
|
@ -13,7 +13,7 @@ function harnessOrigin(webServer, configured) {
|
|||
return new URL(`http://127.0.0.1:${port}`);
|
||||
}
|
||||
|
||||
function pluginPaths(config, channel) {
|
||||
export function pluginPaths(config, channel) {
|
||||
const dshHome = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
|
||||
const root = resolve(config.dataDir ?? join(dshHome, 'integrations', `dsh-${channel}`));
|
||||
return {
|
||||
|
|
|
|||
28
plugin-src/host/channels/slack/index.mjs
Normal file
28
plugin-src/host/channels/slack/index.mjs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { createProductionController } from './production.mjs';
|
||||
import { installSlackRpc } from './rpc.mjs';
|
||||
|
||||
export const name = 'dsh-im-slack-host';
|
||||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) return installSlackRpc(ctx, config.controller, config.rpcAuthority);
|
||||
const production = await createProductionController(ctx, config, config.internals ?? {});
|
||||
const disposeRpc = installSlackRpc(ctx, production.controller, config.rpcAuthority);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close Slack bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
||||
export function createSlackHostPlugin(config) {
|
||||
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
|
||||
}
|
||||
|
||||
export { createProductionController } from './production.mjs';
|
||||
export {
|
||||
SLACK_ENDPOINTS,
|
||||
SLACK_RPC_CHANNEL,
|
||||
SLACK_RPC_ENDPOINTS,
|
||||
createSlackRpcHandler,
|
||||
installSlackRpc,
|
||||
} from './rpc.mjs';
|
||||
export { SlackController } from '../../../../src/channels/slack/slack-controller.mjs';
|
||||
export { SlackRuntime } from '../../../../src/channels/slack/slack-runtime.mjs';
|
||||
91
plugin-src/host/channels/slack/production.mjs
Normal file
91
plugin-src/host/channels/slack/production.mjs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { unlink } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
import { SlackConfigStore } from '../../../../src/channels/slack/config-store.mjs';
|
||||
import { SlackController } from '../../../../src/channels/slack/slack-controller.mjs';
|
||||
import { SlackHarnessClient } from '../../../../src/channels/slack/harness-client.mjs';
|
||||
import { SlackRuntime } from '../../../../src/channels/slack/slack-runtime.mjs';
|
||||
import { SlackStateStore } from '../../../../src/channels/slack/state-store.mjs';
|
||||
import { createTokenConnectionSupervisor } from '../shared/connection-supervisor.mjs';
|
||||
import { harnessOrigin, pluginPaths } from '../shared/production.mjs';
|
||||
|
||||
export async function createProductionController(ctx, config = {}, internals = {}) {
|
||||
if (!ctx?.credentials) throw new TypeError('dsh-im slack requires ctx.credentials');
|
||||
if (!ctx?.webServer) throw new TypeError('dsh-im slack requires ctx.webServer');
|
||||
|
||||
const ResolvedConfigStore = internals.ConfigStore ?? SlackConfigStore;
|
||||
const ResolvedStateStore = internals.StateStore ?? SlackStateStore;
|
||||
const ResolvedHarness = internals.HarnessClient ?? SlackHarnessClient;
|
||||
const ResolvedController = internals.Controller ?? SlackController;
|
||||
const ResolvedRuntime = internals.Runtime ?? SlackRuntime;
|
||||
const createSupervisor = internals.createConnectionSupervisor ?? createTokenConnectionSupervisor;
|
||||
const logger = typeof ctx.logger === 'function'
|
||||
? ctx.logger('dsh-im:slack') : (ctx.logger ?? console);
|
||||
const paths = pluginPaths(config, 'slack');
|
||||
const configStore = await new ResolvedConfigStore(paths.config).load();
|
||||
const stateStores = new Map();
|
||||
const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
|
||||
const stateFor = async (botId) => {
|
||||
let state = stateStores.get(botId);
|
||||
if (!state) {
|
||||
state = await new ResolvedStateStore(statePath(botId)).load();
|
||||
stateStores.set(botId, state);
|
||||
}
|
||||
return state;
|
||||
};
|
||||
const harness = new ResolvedHarness({
|
||||
baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl),
|
||||
workspace: resolve(config.workspace ?? process.cwd()),
|
||||
agentPreset: config.agentPreset ?? 'standard',
|
||||
autostart: false,
|
||||
dshBin: config.dshBin ?? 'dsh',
|
||||
});
|
||||
const controller = new ResolvedController({
|
||||
credentials: ctx.credentials,
|
||||
configStore,
|
||||
logger,
|
||||
...(internals.inspectCredentials ? { inspectCredentials: internals.inspectCredentials } : {}),
|
||||
createRuntime: async ({ botId, config: botConfig, botToken, appToken }) => new ResolvedRuntime({
|
||||
config: botConfig,
|
||||
botToken,
|
||||
appToken,
|
||||
harness,
|
||||
state: await stateFor(botId),
|
||||
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
|
||||
connectTimeoutMs: config.connectTimeoutMs ?? 20_000,
|
||||
logger: {
|
||||
error: (...args) => logger.error?.(`[${botId}]`, ...args),
|
||||
warn: (...args) => logger.warn?.(`[${botId}]`, ...args),
|
||||
info: (...args) => logger.info?.(`[${botId}]`, ...args),
|
||||
debug: (...args) => logger.debug?.(`[${botId}]`, ...args),
|
||||
},
|
||||
}),
|
||||
deleteState: async ({ botId }) => {
|
||||
const state = stateStores.get(botId);
|
||||
stateStores.delete(botId);
|
||||
if (state && typeof state.remove === 'function') return state.remove();
|
||||
try {
|
||||
await unlink(statePath(botId));
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
const supervisor = createSupervisor({
|
||||
channel: 'slack',
|
||||
controller,
|
||||
harness,
|
||||
logger,
|
||||
retryDelaysMs: config.retryDelaysMs,
|
||||
healthyIntervalMs: config.healthyIntervalMs,
|
||||
}).start();
|
||||
return {
|
||||
controller,
|
||||
ready: supervisor.ready,
|
||||
async close() {
|
||||
await supervisor.close();
|
||||
await controller.close();
|
||||
harness.stopManagedProcess();
|
||||
},
|
||||
};
|
||||
}
|
||||
127
plugin-src/host/channels/slack/rpc.mjs
Normal file
127
plugin-src/host/channels/slack/rpc.mjs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const SLACK_RPC_CHANNEL = '/slack';
|
||||
export const SLACK_ENDPOINTS = Object.freeze({
|
||||
status: 'connection.status',
|
||||
bindCredentials: 'bot.bind-credentials',
|
||||
reconnectBot: 'bot.reconnect',
|
||||
deleteBot: 'bot.delete',
|
||||
});
|
||||
export const SLACK_RPC_ENDPOINTS = Object.freeze(Object.values(SLACK_ENDPOINTS));
|
||||
|
||||
const FORBIDDEN_PUBLIC_KEYS = new Set([
|
||||
'token', 'botToken', 'appToken', 'botTokenRef', 'appTokenRef',
|
||||
'tokenRef', 'platformId', 'secret', 'secretRef',
|
||||
]);
|
||||
|
||||
function isRecord(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function exactKeys(value, allowed) {
|
||||
return isRecord(value) && Object.keys(value).every((key) => allowed.includes(key));
|
||||
}
|
||||
|
||||
function validId(value) {
|
||||
return typeof value === 'string' && /^slack_[a-f0-9]{24}$/.test(value);
|
||||
}
|
||||
|
||||
function validBotToken(value) {
|
||||
return typeof value === 'string' && /^xoxb-[A-Za-z0-9-]{16,}$/.test(value.trim())
|
||||
&& value.length <= 4_096;
|
||||
}
|
||||
|
||||
function validAppToken(value) {
|
||||
return typeof value === 'string' && /^xapp-[A-Za-z0-9-]{16,}$/.test(value.trim())
|
||||
&& value.length <= 4_096;
|
||||
}
|
||||
|
||||
function payloadFailure(endpoint, payload) {
|
||||
if (!isRecord(payload)) return 'Payload must be an object.';
|
||||
if (endpoint === SLACK_ENDPOINTS.status) {
|
||||
return exactKeys(payload, []) ? null : 'connection.status does not accept fields.';
|
||||
}
|
||||
if (endpoint === SLACK_ENDPOINTS.bindCredentials) {
|
||||
return exactKeys(payload, ['botToken', 'appToken'])
|
||||
&& validBotToken(payload.botToken) && validAppToken(payload.appToken)
|
||||
? null : 'bot.bind-credentials requires xoxb Bot Token and xapp App Token.';
|
||||
}
|
||||
if (endpoint === SLACK_ENDPOINTS.reconnectBot) {
|
||||
return exactKeys(payload, ['botId']) && validId(payload.botId)
|
||||
? null : 'bot.reconnect requires a botId.';
|
||||
}
|
||||
if (endpoint === SLACK_ENDPOINTS.deleteBot) {
|
||||
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId) && payload.confirm === true
|
||||
? null : 'bot.delete requires a botId and confirm=true.';
|
||||
}
|
||||
return 'Unknown Slack endpoint.';
|
||||
}
|
||||
|
||||
function sanitizePublic(value) {
|
||||
if (Array.isArray(value)) return value.map(sanitizePublic);
|
||||
if (!isRecord(value)) return value;
|
||||
const safe = {};
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (!FORBIDDEN_PUBLIC_KEYS.has(key)) safe[key] = sanitizePublic(child);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
function operationError(error) {
|
||||
if (error?.code === 'slack-invalid-bot-token') {
|
||||
return { code: 'invalid-bot-token', message: 'Slack Bot Token 无效,请确认使用以 xoxb- 开头的令牌。' };
|
||||
}
|
||||
if (error?.code === 'slack-invalid-app-token') {
|
||||
return { code: 'invalid-app-token', message: 'Slack App Token 无效,请确认使用以 xapp- 开头的令牌。' };
|
||||
}
|
||||
if (error?.code === 'slack-missing-scope') {
|
||||
return { code: 'missing-scope', message: 'Slack 应用权限不完整,请重新导入 Manifest 并安装到工作区。' };
|
||||
}
|
||||
if (error?.code === 'slack-socket-mode') {
|
||||
return { code: 'socket-mode-unavailable', message: error.message };
|
||||
}
|
||||
return { code: 'slack-operation-failed', message: 'Slack 操作失败,请稍后重试。' };
|
||||
}
|
||||
|
||||
export function createSlackRpcHandler(controller) {
|
||||
for (const method of ['status', 'bindCredentials', 'reconnectBot', 'deleteBot']) {
|
||||
if (typeof controller?.[method] !== 'function') {
|
||||
throw new TypeError(`A complete Slack controller is required (${method})`);
|
||||
}
|
||||
}
|
||||
return async (endpoint, payload, signal) => {
|
||||
if (signal?.aborted) {
|
||||
return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
|
||||
}
|
||||
if (!SLACK_RPC_ENDPOINTS.includes(endpoint)) {
|
||||
return { ok: false, error: { code: 'bad-request', message: 'Unknown Slack endpoint.' } };
|
||||
}
|
||||
const invalid = payloadFailure(endpoint, payload);
|
||||
if (invalid) return { ok: false, error: { code: 'bad-request', message: invalid } };
|
||||
try {
|
||||
let value;
|
||||
if (endpoint === SLACK_ENDPOINTS.status) value = await controller.status();
|
||||
else if (endpoint === SLACK_ENDPOINTS.bindCredentials) value = await controller.bindCredentials(payload);
|
||||
else if (endpoint === SLACK_ENDPOINTS.reconnectBot) value = await controller.reconnectBot(payload.botId);
|
||||
else value = await controller.deleteBot(payload.botId);
|
||||
return signal?.aborted
|
||||
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
|
||||
: { ok: true, value: sanitizePublic(value) };
|
||||
} catch (error) {
|
||||
return signal?.aborted
|
||||
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
|
||||
: { ok: false, error: operationError(error) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function installSlackRpc(ctx, controller, authority) {
|
||||
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
|
||||
throw new TypeError('DSH Host Connection RPC is required');
|
||||
}
|
||||
return ctx.connection.rpc.handle(
|
||||
SLACK_RPC_CHANNEL,
|
||||
createSlackRpcHandler(controller),
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ import { apply as applyDingtalk } from './channels/dingtalk/index.mjs';
|
|||
import { apply as applyDiscord } from './channels/discord/index.mjs';
|
||||
import { apply as applyFeishu } from './channels/feishu/index.mjs';
|
||||
import { apply as applyQq } from './channels/qq/index.mjs';
|
||||
import { apply as applySlack } from './channels/slack/index.mjs';
|
||||
import { apply as applyTelegram } from './channels/telegram/index.mjs';
|
||||
import { apply as applyWecom } from './channels/wecom/index.mjs';
|
||||
import { apply as applyWeixin } from './channels/weixin/index.mjs';
|
||||
|
|
@ -23,6 +24,7 @@ export function createImHostPlugin(internals = {}) {
|
|||
const startDingtalk = internals.applyDingtalk ?? applyDingtalk;
|
||||
const startWecom = internals.applyWecom ?? applyWecom;
|
||||
const startQq = internals.applyQq ?? applyQq;
|
||||
const startSlack = internals.applySlack ?? applySlack;
|
||||
const startTelegram = internals.applyTelegram ?? applyTelegram;
|
||||
const startDiscord = internals.applyDiscord ?? applyDiscord;
|
||||
const startWhatsapp = internals.applyWhatsapp ?? applyWhatsapp;
|
||||
|
|
@ -35,6 +37,7 @@ export function createImHostPlugin(internals = {}) {
|
|||
await startDingtalk(ctx, channelConfig(config, 'dingtalk'));
|
||||
await startWecom(ctx, channelConfig(config, 'wecom'));
|
||||
await startQq(ctx, channelConfig(config, 'qq'));
|
||||
await startSlack(ctx, channelConfig(config, 'slack'));
|
||||
await startTelegram(ctx, channelConfig(config, 'telegram'));
|
||||
await startDiscord(ctx, channelConfig(config, 'discord'));
|
||||
await startWhatsapp(ctx, channelConfig(config, 'whatsapp'));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue