初始化模版工程
This commit is contained in:
158
remote-control/bots/discord/handlers.ts
Normal file
158
remote-control/bots/discord/handlers.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import type { Client, Message } from 'discord.js'
|
||||
import { HTTPClient } from '@/http'
|
||||
import { getDefaultAgentId } from '@/app/api/nova-config'
|
||||
import { getConversationId, setConversationId } from './user-store'
|
||||
import { sendMessageAndWaitResponse } from '@/remote-control/shared/nova-bridge'
|
||||
import { uploadBotAttachments, type BotAttachment } from '@/remote-control/shared/file-uploader'
|
||||
import { BotLogger } from '@/remote-control/shared/logger'
|
||||
|
||||
const oapiClient = new HTTPClient({
|
||||
baseURL: process.env.NOVA_BASE_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Tenant-Id': process.env.NOVA_TENANT_ID!,
|
||||
'Authorization': process.env.NOVA_ACCESS_KEY!,
|
||||
},
|
||||
})
|
||||
|
||||
const userQueues = new Map<string, Promise<void>>()
|
||||
|
||||
function splitMessage(text: string, maxLength = 2000): string[] {
|
||||
if (text.length <= maxLength) return [text]
|
||||
const parts: string[] = []
|
||||
let remaining = text
|
||||
while (remaining.length > 0) {
|
||||
if (remaining.length <= maxLength) {
|
||||
parts.push(remaining)
|
||||
break
|
||||
}
|
||||
let splitIndex = remaining.lastIndexOf('\n', maxLength)
|
||||
if (splitIndex <= 0) {
|
||||
splitIndex = maxLength
|
||||
}
|
||||
parts.push(remaining.slice(0, splitIndex))
|
||||
remaining = remaining.slice(splitIndex).trimStart()
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
async function getOrCreateConversation(discordUserId: string): Promise<string> {
|
||||
const existing = getConversationId(discordUserId)
|
||||
if (existing) return existing
|
||||
|
||||
const res = await oapiClient.post<{ conversation_id: string }>(
|
||||
'/v1/oapi/super_agent/chat/create_conversation',
|
||||
{
|
||||
agent_id: getDefaultAgentId(),
|
||||
title: `Discord User ${discordUserId}`,
|
||||
},
|
||||
)
|
||||
|
||||
const conversationId = res.conversation_id
|
||||
setConversationId(discordUserId, conversationId)
|
||||
return conversationId
|
||||
}
|
||||
|
||||
async function processMessage(message: Message, onMessage?: () => void): Promise<void> {
|
||||
const content = message.content
|
||||
.replace(/<@!?\d+>/g, '')
|
||||
.trim()
|
||||
|
||||
// Extract attachments from Discord message
|
||||
const attachments: BotAttachment[] = Array.from(message.attachments.values()).map(att => ({
|
||||
url: att.url,
|
||||
fileName: att.name ?? `discord_file_${Date.now()}`,
|
||||
mimeType: att.contentType ?? undefined,
|
||||
size: att.size,
|
||||
}))
|
||||
|
||||
if (!content && attachments.length === 0) return
|
||||
|
||||
BotLogger.log({
|
||||
platform: 'discord',
|
||||
eventType: 'message_received',
|
||||
severity: 'info',
|
||||
message: `收到来自用户 ${message.author.username} 的消息 (${attachments.length} 附件)`,
|
||||
details: { userId: message.author.id, channelId: message.channelId },
|
||||
})
|
||||
|
||||
let typingInterval: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
try {
|
||||
const channel = message.channel
|
||||
if ('sendTyping' in channel) {
|
||||
await channel.sendTyping()
|
||||
}
|
||||
typingInterval = setInterval(() => {
|
||||
if ('sendTyping' in channel) {
|
||||
channel.sendTyping().catch(() => {})
|
||||
}
|
||||
}, 8000)
|
||||
|
||||
// Upload attachments if any
|
||||
let uploadFileIds: string[] | undefined
|
||||
if (attachments.length > 0) {
|
||||
uploadFileIds = await uploadBotAttachments(attachments)
|
||||
if (uploadFileIds.length === 0) uploadFileIds = undefined
|
||||
}
|
||||
|
||||
const conversationId = await getOrCreateConversation(message.author.id)
|
||||
const response = await sendMessageAndWaitResponse(
|
||||
`discord:${message.author.id}`,
|
||||
conversationId,
|
||||
content || '',
|
||||
uploadFileIds,
|
||||
)
|
||||
|
||||
if (!response) {
|
||||
await message.reply('没有收到回复,请稍后重试。')
|
||||
return
|
||||
}
|
||||
|
||||
const parts = splitMessage(response)
|
||||
for (const part of parts) {
|
||||
await message.reply(part)
|
||||
}
|
||||
|
||||
if (onMessage) onMessage()
|
||||
|
||||
BotLogger.log({
|
||||
platform: 'discord',
|
||||
eventType: 'message_sent',
|
||||
severity: 'info',
|
||||
message: `已回复用户 ${message.author.username}`,
|
||||
})
|
||||
} catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : '未知错误'
|
||||
console.error('[Discord Bot] 处理消息失败:', errMsg)
|
||||
await message.reply(`处理消息时出错: ${errMsg}`).catch(() => {})
|
||||
BotLogger.log({
|
||||
platform: 'discord',
|
||||
eventType: 'error',
|
||||
severity: 'error',
|
||||
message: `处理消息失败: ${errMsg}`,
|
||||
details: { userId: message.author.id },
|
||||
})
|
||||
} finally {
|
||||
if (typingInterval) clearInterval(typingInterval)
|
||||
}
|
||||
}
|
||||
|
||||
export function registerHandlers(client: Client, onMessage?: () => void): void {
|
||||
client.on('messageCreate', (message: Message) => {
|
||||
if (message.author.bot) return
|
||||
if (!client.user || !message.mentions.has(client.user)) return
|
||||
|
||||
const userId = message.author.id
|
||||
|
||||
const currentQueue = userQueues.get(userId) ?? Promise.resolve()
|
||||
const newQueue = currentQueue.then(() => processMessage(message, onMessage))
|
||||
userQueues.set(userId, newQueue)
|
||||
|
||||
newQueue.finally(() => {
|
||||
if (userQueues.get(userId) === newQueue) {
|
||||
userQueues.delete(userId)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
147
remote-control/bots/discord/index.ts
Normal file
147
remote-control/bots/discord/index.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import { Client, GatewayIntentBits, Events } from 'discord.js'
|
||||
import { registerHandlers } from './handlers'
|
||||
import { closeConnectionsForPlatform } from '@/remote-control/shared/nova-bridge'
|
||||
import { BotLogger } from '@/remote-control/shared/logger'
|
||||
import { ConfigManager, type ConfigChangeEvent } from '@/remote-control/config/manager'
|
||||
|
||||
let client: Client | null = null
|
||||
let currentToken: string = ''
|
||||
let startTime: number = 0
|
||||
let messagesProcessed: number = 0
|
||||
let lastError: Error | null = null
|
||||
|
||||
export interface BotStatus {
|
||||
platform: string
|
||||
status: 'connected' | 'disconnected' | 'connecting'
|
||||
uptime?: number
|
||||
messagesProcessed: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
export async function startBot(token: string): Promise<void> {
|
||||
if (!token) {
|
||||
const msg = 'Discord Bot Token 为空,跳过启动'
|
||||
console.warn(`[Discord Bot] ${msg}`)
|
||||
BotLogger.log({ platform: 'discord', eventType: 'error', severity: 'warning', message: msg })
|
||||
return
|
||||
}
|
||||
|
||||
currentToken = token
|
||||
|
||||
client = new Client({
|
||||
intents: [
|
||||
GatewayIntentBits.Guilds,
|
||||
GatewayIntentBits.GuildMessages,
|
||||
GatewayIntentBits.MessageContent,
|
||||
],
|
||||
})
|
||||
|
||||
client.once(Events.ClientReady, (readyClient) => {
|
||||
startTime = Date.now()
|
||||
lastError = null
|
||||
console.log(`[Discord Bot] 已登录: ${readyClient.user.tag}`)
|
||||
BotLogger.log({
|
||||
platform: 'discord',
|
||||
eventType: 'connection',
|
||||
severity: 'info',
|
||||
message: `Discord Bot 已连接,用户名: ${readyClient.user.tag}`,
|
||||
})
|
||||
})
|
||||
|
||||
client.on('error', (err) => {
|
||||
lastError = err
|
||||
console.error('[Discord Bot] 运行时错误:', err.message)
|
||||
BotLogger.log({
|
||||
platform: 'discord',
|
||||
eventType: 'error',
|
||||
severity: 'error',
|
||||
message: `Discord Bot 运行时错误: ${err.message}`,
|
||||
})
|
||||
})
|
||||
|
||||
client.on('disconnect', () => {
|
||||
console.warn('[Discord Bot] 连接断开')
|
||||
BotLogger.log({
|
||||
platform: 'discord',
|
||||
eventType: 'disconnection',
|
||||
severity: 'warning',
|
||||
message: 'Discord Bot 连接断开',
|
||||
})
|
||||
})
|
||||
|
||||
registerHandlers(client, () => { messagesProcessed++ })
|
||||
|
||||
try {
|
||||
await client.login(token)
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err))
|
||||
lastError = error
|
||||
client = null
|
||||
currentToken = ''
|
||||
console.error('[Discord Bot] 登录失败:', error.message)
|
||||
BotLogger.log({
|
||||
platform: 'discord',
|
||||
eventType: 'error',
|
||||
severity: 'error',
|
||||
message: `Discord Bot 登录失败: ${error.message}`,
|
||||
details: { hint: '请检查 Bot Token 是否正确,以及是否已在 Discord Developer Portal 中启用了 Bot' },
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function stopBot(): Promise<void> {
|
||||
closeConnectionsForPlatform('discord')
|
||||
if (client) {
|
||||
client.destroy()
|
||||
client = null
|
||||
currentToken = ''
|
||||
startTime = 0
|
||||
console.log('[Discord Bot] 已停止')
|
||||
BotLogger.log({
|
||||
platform: 'discord',
|
||||
eventType: 'disconnection',
|
||||
severity: 'info',
|
||||
message: 'Discord Bot 已停止',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function getStatus(): BotStatus {
|
||||
return {
|
||||
platform: 'discord',
|
||||
status: client ? 'connected' : 'disconnected',
|
||||
uptime: client && startTime ? Math.floor((Date.now() - startTime) / 1000) : undefined,
|
||||
messagesProcessed,
|
||||
error: lastError?.message,
|
||||
}
|
||||
}
|
||||
|
||||
// 监听配置变更
|
||||
const configManager = ConfigManager.getInstance()
|
||||
configManager.on('config-changed', async (event: ConfigChangeEvent) => {
|
||||
const { newConfig } = event
|
||||
const platformConfig = newConfig.discord
|
||||
|
||||
try {
|
||||
if (platformConfig.enabled && !client) {
|
||||
await startBot(platformConfig.botToken)
|
||||
} else if (!platformConfig.enabled && client) {
|
||||
await stopBot()
|
||||
} else if (platformConfig.enabled && client) {
|
||||
if (platformConfig.botToken !== currentToken) {
|
||||
await stopBot()
|
||||
await startBot(platformConfig.botToken)
|
||||
}
|
||||
}
|
||||
lastError = null
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error(String(error))
|
||||
BotLogger.log({
|
||||
platform: 'discord',
|
||||
eventType: 'error',
|
||||
severity: 'error',
|
||||
message: `配置变更处理失败: ${lastError.message}`,
|
||||
})
|
||||
}
|
||||
})
|
||||
45
remote-control/bots/discord/user-store.ts
Normal file
45
remote-control/bots/discord/user-store.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
interface UserMapping {
|
||||
conversationId: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
type UserStore = Record<string, UserMapping>
|
||||
|
||||
const STORE_PATH = path.join(process.cwd(), 'remote-control', 'data', 'discord-users.json')
|
||||
|
||||
function readStore(): UserStore {
|
||||
try {
|
||||
if (!fs.existsSync(STORE_PATH)) {
|
||||
return {}
|
||||
}
|
||||
const data = fs.readFileSync(STORE_PATH, 'utf-8')
|
||||
return JSON.parse(data)
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
function writeStore(store: UserStore): void {
|
||||
const dir = path.dirname(STORE_PATH)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
fs.writeFileSync(STORE_PATH, JSON.stringify(store, null, 2), 'utf-8')
|
||||
}
|
||||
|
||||
export function getConversationId(discordUserId: string): string | null {
|
||||
const store = readStore()
|
||||
return store[discordUserId]?.conversationId ?? null
|
||||
}
|
||||
|
||||
export function setConversationId(discordUserId: string, conversationId: string): void {
|
||||
const store = readStore()
|
||||
store[discordUserId] = {
|
||||
conversationId,
|
||||
createdAt: new Date().toISOString(),
|
||||
}
|
||||
writeStore(store)
|
||||
}
|
||||
Reference in New Issue
Block a user