初始化模版工程

This commit is contained in:
Cloud Bot
2026-03-20 07:33:46 +00:00
commit 23717e0ecd
386 changed files with 51675 additions and 0 deletions

View File

@@ -0,0 +1,251 @@
import type { Bot, Context } from 'grammy'
import { InputFile } from 'grammy'
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 = 4096): 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(telegramUserId: string, name: string): Promise<string> {
const existing = getConversationId(telegramUserId)
if (existing) return existing
const agentId = getDefaultAgentId()
const res = await oapiClient.post<{ conversation_id: string }>(
'/v1/oapi/super_agent/chat/create_conversation',
{
agent_id: agentId,
title: `Telegram User ${name || telegramUserId}`,
},
)
const conversationId = res.conversation_id
setConversationId(telegramUserId, conversationId, name)
return conversationId
}
async function processMessage(
ctx: Context,
botToken: string,
onMessage?: () => void,
): Promise<void> {
const message = ctx.message
if (!message) return
const userId = String(message.from?.id ?? '')
const userName = message.from?.username || message.from?.first_name || userId
// Extract text
const text = (message.text || message.caption || '').trim()
// Extract attachments
const attachments: BotAttachment[] = []
// Handle photos - take the last one (largest size)
if (message.photo && message.photo.length > 0) {
const largestPhoto = message.photo[message.photo.length - 1]
try {
const file = await ctx.api.getFile(largestPhoto.file_id)
if (file.file_path) {
const downloadUrl = `https://api.telegram.org/file/bot${botToken}/${file.file_path}`
attachments.push({
url: downloadUrl,
fileName: `telegram_photo_${Date.now()}.jpg`,
mimeType: 'image/jpeg',
size: largestPhoto.file_size,
})
}
} catch (err) {
console.error('[Telegram Bot] 获取图片文件失败:', err)
}
}
// Handle documents
if (message.document) {
try {
const file = await ctx.api.getFile(message.document.file_id)
if (file.file_path) {
const downloadUrl = `https://api.telegram.org/file/bot${botToken}/${file.file_path}`
attachments.push({
url: downloadUrl,
fileName: message.document.file_name || `telegram_file_${Date.now()}`,
mimeType: message.document.mime_type ?? undefined,
size: message.document.file_size,
})
}
} catch (err) {
console.error('[Telegram Bot] 获取文档文件失败:', err)
}
}
if (!text && attachments.length === 0) return
BotLogger.log({
platform: 'telegram',
eventType: 'message_received',
severity: 'info',
message: `收到来自用户 ${userName} 的消息 (${attachments.length} 附件)`,
details: { userId, chatId: String(message.chat.id) },
})
try {
// Send typing action
await ctx.api.sendChatAction(message.chat.id, 'typing').catch(() => {})
const typingInterval = setInterval(() => {
ctx.api.sendChatAction(message.chat.id, 'typing').catch(() => {})
}, 5000)
try {
// 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(userId, userName)
const response = await sendMessageAndWaitResponse(
`telegram:${userId}`,
conversationId,
text || '',
uploadFileIds,
)
if (!response) {
await ctx.reply('没有收到回复,请稍后重试。')
return
}
// Check for Markdown image syntax in response
const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g
const images: Array<{ alt: string; url: string }> = []
let match: RegExpExecArray | null
while ((match = imageRegex.exec(response)) !== null) {
images.push({ alt: match[1], url: match[2] })
}
if (images.length > 0) {
// Remove image markdown from text
const textWithoutImages = response.replace(imageRegex, '').trim()
// Send images with caption
for (let i = 0; i < images.length; i++) {
const image = images[i]
try {
if (i === 0 && textWithoutImages) {
// First image with caption (Telegram caption limit: 1024 chars)
if (textWithoutImages.length <= 1024) {
await ctx.replyWithPhoto(image.url, {
caption: textWithoutImages,
parse_mode: 'HTML',
})
} else {
// Caption too long - send photo first, then text separately
await ctx.replyWithPhoto(image.url)
const textParts = splitMessage(textWithoutImages)
for (const part of textParts) {
await ctx.reply(part)
}
}
} else {
await ctx.replyWithPhoto(image.url)
}
} catch {
// If photo sending fails, send as link
await ctx.reply(`${image.alt || '图片'}: ${image.url}`)
}
}
// If no caption was sent with the first image and there's text
if (images.length > 0 && textWithoutImages && textWithoutImages.length > 1024) {
// Already handled above
}
} else {
// Plain text response
const parts = splitMessage(response)
for (const part of parts) {
await ctx.reply(part)
}
}
if (onMessage) onMessage()
BotLogger.log({
platform: 'telegram',
eventType: 'message_sent',
severity: 'info',
message: `已回复用户 ${userName}`,
})
} finally {
clearInterval(typingInterval)
}
} catch (error) {
const errMsg = error instanceof Error ? error.message : '未知错误'
console.error('[Telegram Bot] 处理消息失败:', errMsg)
await ctx.reply(`处理消息时出错: ${errMsg}`).catch(() => {})
BotLogger.log({
platform: 'telegram',
eventType: 'error',
severity: 'error',
message: `处理消息失败: ${errMsg}`,
details: { userId },
})
}
}
export function registerHandlers(bot: Bot, botToken: string, onMessage?: () => void): void {
const handleMessage = (ctx: Context) => {
const userId = String(ctx.message?.from?.id ?? '')
if (!userId) return
// Filter bot's own messages
if (ctx.message?.from?.is_bot) return
const currentQueue = userQueues.get(userId) ?? Promise.resolve()
const newQueue = currentQueue.then(() => processMessage(ctx, botToken, onMessage))
userQueues.set(userId, newQueue)
newQueue.finally(() => {
if (userQueues.get(userId) === newQueue) {
userQueues.delete(userId)
}
})
}
bot.on('message:text', handleMessage)
bot.on('message:photo', handleMessage)
bot.on('message:document', handleMessage)
}

View File

@@ -0,0 +1,185 @@
import { Bot } from 'grammy'
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'
const CONNECTION_TIMEOUT = 30_000 // 30s to establish first connection
let bot: Bot | null = null
let currentToken: string = ''
let isConnected: boolean = false
let connectTimer: ReturnType<typeof setTimeout> | null = null
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 = 'Telegram Bot Token 为空,跳过启动'
console.warn(`[Telegram Bot] ${msg}`)
BotLogger.log({ platform: 'telegram', eventType: 'error', severity: 'warning', message: msg })
return
}
// Idempotent check
if (bot && currentToken === token) {
console.log('[Telegram Bot] 已有活跃连接,跳过重复启动')
return
}
// If token changed, stop old bot first
if (bot) {
console.log('[Telegram Bot] Token 已变更,先停止旧连接')
await stopBot()
}
currentToken = token
try {
bot = new Bot(token)
bot.catch((err) => {
lastError = err.error instanceof Error ? err.error : new Error(String(err.error))
console.error('[Telegram Bot] 运行时错误:', lastError.message)
BotLogger.log({
platform: 'telegram',
eventType: 'error',
severity: 'error',
message: `Telegram Bot 运行时错误: ${lastError.message}`,
})
})
registerHandlers(bot, token, () => { messagesProcessed++ })
// Connection timeout — if onStart is not called within CONNECTION_TIMEOUT,
// stop the bot and mark as disconnected
connectTimer = setTimeout(() => {
if (!isConnected && bot) {
const msg = '连接超时,请检查 Token 是否正确以及网络是否可达'
lastError = new Error(msg)
console.error(`[Telegram Bot] ${msg}`)
BotLogger.log({ platform: 'telegram', eventType: 'error', severity: 'error', message: msg })
void stopBot()
}
}, CONNECTION_TIMEOUT)
// Start long polling (non-blocking).
// bot.start() returns a promise that resolves when bot.stop() is called,
// so we must NOT await it. Connection errors surface via bot.catch().
bot.start({
onStart: (botInfo) => {
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null }
isConnected = true
startTime = Date.now()
lastError = null
console.log(`[Telegram Bot] 已启动: @${botInfo.username}`)
BotLogger.log({
platform: 'telegram',
eventType: 'connection',
severity: 'info',
message: `Telegram Bot 已连接,用户名: @${botInfo.username}`,
})
},
}).catch((err) => {
// Long polling loop ended with error (e.g. invalid token, network issue)
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null }
const error = err instanceof Error ? err : new Error(String(err))
if (error.message === 'Aborted delay') return // Normal stop, ignore
lastError = error
isConnected = false
console.error('[Telegram Bot] 长轮询异常退出:', error.message)
BotLogger.log({
platform: 'telegram',
eventType: 'error',
severity: 'error',
message: `Telegram Bot 长轮询异常: ${error.message}`,
})
})
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err))
lastError = error
bot = null
currentToken = ''
isConnected = false
console.error('[Telegram Bot] 启动失败:', error.message)
BotLogger.log({
platform: 'telegram',
eventType: 'error',
severity: 'error',
message: `Telegram Bot 启动失败: ${error.message}`,
details: { hint: '请检查 Bot Token 是否正确,以及是否已在 @BotFather 中创建了 Bot' },
})
throw error
}
}
export async function stopBot(): Promise<void> {
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null }
closeConnectionsForPlatform('telegram')
if (bot) {
try {
await bot.stop()
} catch {
// "Aborted delay" is expected when stopping long polling — ignore
}
bot = null
currentToken = ''
isConnected = false
startTime = 0
console.log('[Telegram Bot] 已停止')
BotLogger.log({
platform: 'telegram',
eventType: 'disconnection',
severity: 'info',
message: 'Telegram Bot 已停止',
})
}
}
export function getStatus(): BotStatus {
return {
platform: 'telegram',
status: isConnected ? 'connected' : bot ? 'connecting' : 'disconnected',
uptime: isConnected && startTime ? Math.floor((Date.now() - startTime) / 1000) : undefined,
messagesProcessed,
error: lastError?.message,
}
}
// Listen for config changes
const configManager = ConfigManager.getInstance()
configManager.on('config-changed', async (event: ConfigChangeEvent) => {
const { newConfig } = event
const platformConfig = newConfig.telegram
try {
if (platformConfig.enabled && !bot) {
await startBot(platformConfig.botToken)
} else if (!platformConfig.enabled && bot) {
await stopBot()
} else if (platformConfig.enabled && bot) {
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: 'telegram',
eventType: 'error',
severity: 'error',
message: `配置变更处理失败: ${lastError.message}`,
})
}
})

View File

@@ -0,0 +1,47 @@
import fs from 'node:fs'
import path from 'node:path'
interface UserMapping {
conversationId: string
name: string
createdAt: string
}
type UserStore = Record<string, UserMapping>
const STORE_PATH = path.join(process.cwd(), 'remote-control', 'data', 'telegram-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(telegramUserId: string): string | null {
const store = readStore()
return store[telegramUserId]?.conversationId ?? null
}
export function setConversationId(telegramUserId: string, conversationId: string, name: string): void {
const store = readStore()
store[telegramUserId] = {
conversationId,
name,
createdAt: new Date().toISOString(),
}
writeStore(store)
}