Add Telegram and Discord IM channels

This commit is contained in:
xmanrui 2026-08-16 14:47:16 +08:00
parent 7123fce47a
commit cb74e1c4c7
66 changed files with 8579 additions and 1910 deletions

View file

@ -0,0 +1,11 @@
import { TOKEN_BOT_ENDPOINTS, createTokenChannelApi } from '../shared/token-api.js';
export const DISCORD_RPC_CHANNEL = '/discord';
export const DISCORD_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
const api = createTokenChannelApi('Discord', ' Gateway 长连接');
export const unwrapRpcResult = api.unwrapRpcResult;
export const normalizeSnapshot = api.normalizeSnapshot;
export const presentError = api.presentError;
export { api as discordClientApi };

View file

@ -0,0 +1,25 @@
import { DiscordLogoGlyph } from '../../channel-logos.js';
import { createTokenChannelSettings } from '../shared/token-channel.js';
import {
DISCORD_ENDPOINTS,
discordClientApi,
} from './api.js';
import { installDiscordStyles } from './styles.js';
const channel = createTokenChannelSettings({
channel: 'Discord',
endpoints: DISCORD_ENDPOINTS,
api: discordClientApi,
LogoGlyph: DiscordLogoGlyph,
installStyles: installDiscordStyles,
pageClass: 'ddc-page',
avatarClass: 'ddc-avatar',
connectionLabel: 'Gateway 长连接',
tokenPlaceholder: '填写 Discord Developer Portal 的 Bot Token',
emptyTitle: '接入 Discord 机器人',
emptyDescription: '先在 Developer Portal 创建 Bot 并邀请到服务器,再在这里完成接入。',
platformLabel: 'Discord Developer Portal',
});
export const DiscordSettingsTab = channel.SettingsTab;
export const DiscordAccountCard = channel.AccountCard;

View file

@ -0,0 +1,19 @@
export const DISCORD_STYLE_ID = 'xmanrui-dsh-im-discord-settings';
const CSS = String.raw`
.ddc-page { --ddt-accent: #5865f2; --ddt-accent-deep: #4752c4; --ddt-accent-wash: #eef0ff; }
.ddc-avatar { color: #fff; background: #5865f2; }
.ddc-avatar svg { display: block; }
`;
export function installDiscordStyles() {
if (typeof document === 'undefined') return () => {};
const existing = document.querySelector(`style[data-plugin-css="${DISCORD_STYLE_ID}"]`);
if (existing) return () => {};
const style = document.createElement('style');
style.dataset.plugin = '@xmanrui/dsh-im';
style.dataset.pluginCss = DISCORD_STYLE_ID;
style.textContent = CSS;
document.head.appendChild(style);
return () => style.remove();
}

View file

@ -0,0 +1,88 @@
const ACCOUNT_STATES = new Set(['connected', 'connecting', 'offline', 'error']);
function isRecord(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function text(value, fallback, max = 240) {
return typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : fallback;
}
function id(value) {
const result = text(value, '', 128);
return /^[a-z\d_-]+$/i.test(result) ? result : undefined;
}
function timestamp(value) {
if (typeof value === 'number' && Number.isFinite(value)) return value;
const parsed = typeof value === 'string' ? Date.parse(value) : Number.NaN;
return Number.isNaN(parsed) ? undefined : parsed;
}
export const TOKEN_BOT_ENDPOINTS = Object.freeze({
status: 'connection.status',
bindCredentials: 'bot.bind-credentials',
reconnectBot: 'bot.reconnect',
deleteBot: 'bot.delete',
});
export function createTokenChannelApi(channel, connectionSummary) {
const unwrapRpcResult = (result) => {
if (!isRecord(result) || typeof result.ok !== 'boolean') {
throw new Error(`${channel} 服务返回了无法识别的响应`);
}
if (!result.ok) {
const error = new Error(text(result.error?.message, `${channel} 操作失败`));
error.code = text(result.error?.code, `${channel.toUpperCase()}_RPC_ERROR`, 80);
throw error;
}
return result.value;
};
const normalizeBot = (value) => {
if (!isRecord(value) || !id(value.botId)) return undefined;
const connected = value.connected === true;
const state = ACCOUNT_STATES.has(value.state) ? value.state : 'offline';
return {
botId: id(value.botId),
connected,
state: connected ? 'connected' : state,
bot: {
name: text(value.bot?.name, `${channel}机器人`, 100),
username: text(value.bot?.username, '', 100),
idMasked: text(value.bot?.idMasked, '机器人标识已安全保存', 140),
},
health: {
summary: text(
value.health?.summary,
connected ? `${channel}${connectionSummary}运行正常` : `${channel}连接尚未就绪`,
),
lastCheckedAt: timestamp(value.health?.lastCheckedAt),
},
error: isRecord(value.error) ? {
code: text(value.error.code, `${channel.toUpperCase()}_ACCOUNT_ERROR`, 80),
message: text(value.error.message, `${channel}连接尚未就绪`),
} : null,
};
};
const normalizeSnapshot = (value) => {
const source = isRecord(value?.snapshot) ? value.snapshot : value;
if (!isRecord(source) || !Array.isArray(source.bots)) {
throw new Error(`${channel} 服务没有返回有效的机器人列表`);
}
const bots = source.bots.map(normalizeBot).filter(Boolean);
return {
revision: Number.isSafeInteger(source.revision) ? source.revision : 0,
bots,
totals: { configured: bots.length, connected: bots.filter((bot) => bot.connected).length },
};
};
const presentError = (error) => ({
code: text(error?.code, `${channel.toUpperCase()}_ERROR`, 80),
message: text(error?.message, `${channel}操作失败,请稍后重试`),
});
return Object.freeze({ unwrapRpcResult, normalizeSnapshot, presentError });
}

View file

@ -0,0 +1,277 @@
import * as React from 'react';
import { CredentialActionIcon, CredentialBindingPanel } from '../../credential-binding.js';
import { installDingtalkStyles } from '../dingtalk/styles.js';
const h = React.createElement;
const Button = React.forwardRef(function Button(
{ children, kind = 'secondary', className = '', ...props },
ref,
) {
return h('button', {
...props,
ref,
type: 'button',
className: `ddt-button ${className}`.trim(),
'data-kind': kind,
}, children);
});
function checkedTime(value) {
if (!value) return '尚未检查';
try {
return new Intl.DateTimeFormat('zh-CN', {
hour: '2-digit', minute: '2-digit', second: '2-digit',
}).format(new Date(value));
} catch {
return '刚刚';
}
}
export function createTokenChannelSettings(definition) {
const {
channel,
endpoints,
api,
LogoGlyph,
installStyles,
pageClass,
avatarClass,
connectionLabel,
tokenPlaceholder,
emptyTitle,
emptyDescription,
platformLabel,
} = definition;
function AccountCard({ account, busy, removing, onReconnect, onRequestRemove, onConfirmRemove, onCancelRemove }) {
const state = busy === 'reconnect' ? 'connecting' : account.state;
const tone = account.connected ? 'success' : state === 'error' ? 'error' : 'warning';
const stateLabel = account.connected ? '运行正常' : state === 'connecting' ? '正在连接' : '连接未就绪';
const summary = account.error?.message ?? (account.connected ? null : account.health.summary);
const identity = account.bot.username ? `@${account.bot.username}` : account.bot.idMasked;
return h('article', { className: 'ddt-card dim-botCard', 'data-bot-id': account.botId },
h('div', { className: 'ddt-cardBody dim-botCardBody' },
h('div', { className: 'ddt-accountTop dim-botCardTop' },
h('div', { className: 'ddt-accountIdentity dim-botIdentity' },
h('div', { className: `ddt-avatar dim-botAvatar ${avatarClass}`, 'aria-hidden': 'true' },
h(LogoGlyph, { size: 29 })),
h('div', { className: 'dim-botName' },
h('h3', null, account.bot.name), h('p', null, identity))),
h('div', { className: 'ddt-health dim-botHealth' },
h('span', { className: 'ddt-dot dim-healthDot', 'data-tone': tone }),
h('span', null, stateLabel))),
h('dl', { className: 'ddt-metrics dim-botMetrics' },
h('div', { className: 'ddt-metric dim-botMetric' },
h('dt', null, '消息通道'), h('dd', null, account.connected ? connectionLabel : '离线')),
h('div', { className: 'ddt-metric dim-botMetric' },
h('dt', null, '最近检查'), h('dd', null, checkedTime(account.health.lastCheckedAt)))),
h('div', { className: 'ddt-accountFooter dim-cardFooter' },
summary ? h('div', { className: 'ddt-summary dim-cardSummary' }, summary) : null,
h('div', { className: 'ddt-actions dim-cardActions' },
h(Button, {
className: 'dim-cardAction',
onClick: onReconnect,
disabled: Boolean(busy),
}, busy === 'reconnect' ? '检查中…' : account.connected ? '检查连接' : '重试连接'),
h(Button, {
className: 'dim-cardAction',
kind: 'danger',
onClick: onRequestRemove,
disabled: Boolean(busy),
}, '移除接入')))),
removing ? h('div', { className: 'ddt-confirm dim-confirm', role: 'alertdialog' },
h('strong', null, `从 DeepSeek Harness 移除“${account.bot.name}”?`),
h('p', null, `这会停止消息连接,并删除本机保存的 Bot Token、机器人配置及会话映射。${platformLabel}中的机器人不会被自动删除。`),
h('div', { className: 'ddt-actions dim-viewActions' },
h(Button, { onClick: onCancelRemove, disabled: Boolean(busy) }, '保留机器人'),
h(Button, { kind: 'danger', onClick: onConfirmRemove, disabled: Boolean(busy) },
busy === 'delete' ? '正在移除…' : '确认移除接入'))) : null);
}
function SettingsTab({ rpcCall }) {
const [model, setModel] = React.useState({
phase: 'loading', bots: [], totals: { configured: 0, connected: 0 }, error: null,
});
const [credentialOpen, setCredentialOpen] = React.useState(false);
const [credentialError, setCredentialError] = React.useState(null);
const [busy, setBusy] = React.useState(false);
const [busyByBot, setBusyByBot] = React.useState({});
const [removeTarget, setRemoveTarget] = React.useState(null);
const mounted = React.useRef(true);
React.useEffect(() => {
const disposeDingtalk = installDingtalkStyles();
const disposeChannel = installStyles();
mounted.current = true;
return () => {
mounted.current = false;
disposeChannel();
disposeDingtalk();
};
}, []);
const invoke = React.useCallback(async (endpoint, payload = {}, signal) => {
if (typeof rpcCall !== 'function') throw new TypeError(`${channel} 设置页缺少 RPC 连接`);
return api.unwrapRpcResult(await rpcCall(endpoint, payload, signal));
}, [rpcCall]);
const loadStatus = React.useCallback(async ({ signal, silent = false } = {}) => {
if (!silent && mounted.current) setModel((current) => ({ ...current, phase: 'loading', error: null }));
try {
const snapshot = api.normalizeSnapshot(await invoke(endpoints.status, {}, signal));
if (!mounted.current || signal?.aborted) return;
setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null });
} catch (error) {
if (error?.name !== 'AbortError' && mounted.current && !signal?.aborted) {
setModel((current) => ({
...current,
phase: silent ? current.phase : 'error',
error: api.presentError(error),
}));
}
}
}, [invoke]);
React.useEffect(() => {
const controller = new AbortController();
void loadStatus({ signal: controller.signal });
return () => controller.abort();
}, [loadStatus]);
React.useEffect(() => {
if (model.phase !== 'ready') return undefined;
const controller = new AbortController();
const timer = window.setInterval(
() => void loadStatus({ signal: controller.signal, silent: true }),
15_000,
);
return () => {
controller.abort();
window.clearInterval(timer);
};
}, [loadStatus, model.phase]);
const bindCredentials = React.useCallback(async ({ secret }) => {
setBusy(true);
setCredentialError(null);
try {
const snapshot = api.normalizeSnapshot(await invoke(endpoints.bindCredentials, { token: secret }));
if (!mounted.current) return;
setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null });
setCredentialOpen(false);
} catch (error) {
if (mounted.current) setCredentialError(api.presentError(error));
} finally {
if (mounted.current) setBusy(false);
}
}, [invoke]);
const botAction = React.useCallback(async (account, operation, endpoint, payload) => {
setBusyByBot((current) => ({ ...current, [account.botId]: operation }));
try {
const snapshot = api.normalizeSnapshot(await invoke(endpoint, payload));
if (mounted.current) {
setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null });
}
} finally {
if (mounted.current) setBusyByBot((current) => {
const next = { ...current };
delete next[account.botId];
return next;
});
}
}, [invoke]);
const botList = model.bots.length > 0
? h('section', { className: 'dim-listSection' },
h('div', { className: 'ddt-listHeading dim-listHeading' },
h('h3', null, `已接入的 ${channel} 机器人`)),
h('ul', { className: 'ddt-list dim-botList' }, model.bots.map((account) =>
h('li', { key: account.botId }, h(AccountCard, {
account,
busy: busyByBot[account.botId],
removing: removeTarget === account.botId,
onReconnect: () => void botAction(
account,
'reconnect',
endpoints.reconnectBot,
{ botId: account.botId },
),
onRequestRemove: () => setRemoveTarget(account.botId),
onCancelRemove: () => setRemoveTarget(null),
onConfirmRemove: async () => {
await botAction(account, 'delete', endpoints.deleteBot, {
botId: account.botId,
confirm: true,
});
if (mounted.current) setRemoveTarget(null);
},
})))))
: null;
return h('section', {
className: `ddt-page ${pageClass} dim-channelPage`,
'aria-label': `${channel} 设置`,
},
h('div', { className: 'ddt-heading' },
h('div', { className: 'ddt-tools' },
h('div', { className: 'dim-bindActions' },
h(Button, {
kind: 'credential',
className: 'dim-credentialButton',
onClick: () => { setCredentialOpen((value) => !value); setCredentialError(null); },
disabled: busy,
'aria-pressed': credentialOpen,
'aria-label': `使用 Bot Token 接入 ${channel} 机器人`,
}, h(CredentialActionIcon), credentialOpen ? '收起凭据' : '手动接入')),
model.totals.configured > 0
? h('div', { className: 'ddt-badge dim-onlineBadge' },
h('span', null, `${model.totals.connected} / ${model.totals.configured} 在线`))
: null)),
model.phase === 'loading'
? h('div', {
className: 'ddt-card ddt-loading dim-surfaceCard dim-loadingView',
'aria-busy': 'true',
}, h('div', { className: 'ddt-spinner dim-spinner' }), `正在读取 ${channel} 机器人状态…`)
: model.phase === 'error'
? h('div', { className: 'ddt-card dim-surfaceCard' },
h('div', { className: 'ddt-inlineError dim-inlineError' },
h('h3', null, `无法读取 ${channel} 机器人状态`),
h('p', null, model.error?.message),
h(Button, { onClick: () => void loadStatus() }, '重新读取')))
: h(React.Fragment, null,
credentialOpen ? h(CredentialBindingPanel, {
channel,
secretLabel: 'Bot Token',
secretPlaceholder: tokenPlaceholder,
busy,
error: credentialError,
onSubmit: bindCredentials,
onCancel: () => { setCredentialOpen(false); setCredentialError(null); },
}) : null,
model.bots.length === 0 && !credentialOpen
? h('div', { className: 'ddt-card dim-surfaceCard' },
h('div', { className: 'ddt-cardBody ddt-empty dim-surfaceBody dim-emptyView' },
h('div', { className: 'dim-emptyCopy' },
h('div', { className: 'ddt-stateLabel dim-stateLabel' },
h('span', { className: 'ddt-dot dim-stateDot' }),
h('span', null, `尚未接入 ${channel} 机器人`)),
h('h3', null, emptyTitle),
h('p', null, emptyDescription),
h('div', { className: 'ddt-actions dim-viewActions' },
h(Button, {
kind: 'primary',
onClick: () => setCredentialOpen(true),
}, '填写 Bot Token'))),
h('div', {
className: `ddt-brandMark dim-emptyBrand ${avatarClass}`,
'aria-hidden': 'true',
}, h(LogoGlyph, { size: 64 }))))
: null,
botList));
}
return { SettingsTab, AccountCard };
}

View file

@ -0,0 +1,11 @@
import { TOKEN_BOT_ENDPOINTS, createTokenChannelApi } from '../shared/token-api.js';
export const TELEGRAM_RPC_CHANNEL = '/telegram';
export const TELEGRAM_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
const api = createTokenChannelApi('Telegram', ' Bot API 长轮询');
export const unwrapRpcResult = api.unwrapRpcResult;
export const normalizeSnapshot = api.normalizeSnapshot;
export const presentError = api.presentError;
export { api as telegramClientApi };

View file

@ -0,0 +1,25 @@
import { TelegramLogoGlyph } from '../../channel-logos.js';
import { createTokenChannelSettings } from '../shared/token-channel.js';
import {
TELEGRAM_ENDPOINTS,
telegramClientApi,
} from './api.js';
import { installTelegramStyles } from './styles.js';
const channel = createTokenChannelSettings({
channel: 'Telegram',
endpoints: TELEGRAM_ENDPOINTS,
api: telegramClientApi,
LogoGlyph: TelegramLogoGlyph,
installStyles: installTelegramStyles,
pageClass: 'dtg-page',
avatarClass: 'dtg-avatar',
connectionLabel: 'Bot API 长轮询',
tokenPlaceholder: '填写 @BotFather 生成的 Bot Token',
emptyTitle: '接入 Telegram 机器人',
emptyDescription: '先通过 @BotFather 获取 Bot Token,再在这里完成接入。',
platformLabel: 'Telegram',
});
export const TelegramSettingsTab = channel.SettingsTab;
export const TelegramAccountCard = channel.AccountCard;

View file

@ -0,0 +1,19 @@
export const TELEGRAM_STYLE_ID = 'xmanrui-dsh-im-telegram-settings';
const CSS = String.raw`
.dtg-page { --ddt-accent: #229ed9; --ddt-accent-deep: #1687bd; --ddt-accent-wash: #eaf7fd; }
.dtg-avatar { color: #fff; background: #229ed9; }
.dtg-avatar svg { display: block; }
`;
export function installTelegramStyles() {
if (typeof document === 'undefined') return () => {};
const existing = document.querySelector(`style[data-plugin-css="${TELEGRAM_STYLE_ID}"]`);
if (existing) return () => {};
const style = document.createElement('style');
style.dataset.plugin = '@xmanrui/dsh-im';
style.dataset.pluginCss = TELEGRAM_STYLE_ID;
style.textContent = CSS;
document.head.appendChild(style);
return () => style.remove();
}