Files
cwd/cwd-api/src/api/telegram/webhook.ts
anghunk e1568f60ff feat(telegram): 新增 Telegram 机器人通知与快捷审核功能
- 新增 Telegram 通知功能,支持通过机器人接收新评论通知
- 在 Telegram 消息中提供“批准”和“删除”按钮,支持快捷审核
- 新增后台 Telegram 设置页面,支持配置 Bot Token、Chat ID 和开关
- 新增 `/api/telegram/webhook` 端点处理按钮回调
- 更新邮件通知逻辑,统一使用评论设置中的 `adminEmail` 作为收件人
- 更新相关文档,包括功能说明和 API 文档
2026-01-30 17:49:47 +08:00

55 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Context } from 'hono';
import { Bindings } from '../../bindings';
import { loadTelegramSettings, editMessageText, answerCallbackQuery } from '../../utils/telegram';
export const telegramWebhook = async (c: Context<{ Bindings: Bindings }>) => {
try {
const settings = await loadTelegramSettings(c.env);
if (!settings.botToken) {
return c.text('Bot token not configured', 400);
}
const update = await c.req.json();
const { callback_query } = update;
if (callback_query) {
await handleCallbackQuery(c, settings.botToken, callback_query);
}
return c.text('OK');
} catch (e: any) {
console.error('Telegram Webhook Error:', e);
return c.text('Internal Server Error', 500);
}
};
async function handleCallbackQuery(c: Context<{ Bindings: Bindings }>, token: string, query: any) {
const { data, message, id } = query;
const chatId = message.chat.id;
const messageId = message.message_id;
if (!data) return;
const [action, commentIdStr] = data.split(':');
const commentId = parseInt(commentIdStr);
if (isNaN(commentId)) {
await answerCallbackQuery(token, id, 'Invalid Comment ID');
return;
}
if (action === 'approve') {
await c.env.CWD_DB.prepare('UPDATE Comment SET status = ? WHERE id = ?').bind('approved', commentId).run();
const newText = message.text + '\n\n✅ 已批准 (Approved)';
await editMessageText(token, chatId, messageId, newText);
await answerCallbackQuery(token, id, '评论已批准');
} else if (action === 'delete') {
await c.env.CWD_DB.prepare('DELETE FROM Comment WHERE id = ?').bind(commentId).run();
const newText = message.text + '\n\n🗑 已删除 (Deleted)';
await editMessageText(token, chatId, messageId, newText);
await answerCallbackQuery(token, id, '评论已删除');
}
}