1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
| require('dotenv').config(); const express = require('express'); const cors = require('cors'); const path = require('path'); const axios = require('axios');
const app = express(); const PORT = process.env.PORT || 3000;
// 中间件配置 app.use(cors()); app.use(express.json()); app.use(express.static('public'));
// 缓存机制let cachedPosts = []; let lastFetchTime = 0; const CACHE_DURATION = parseInt(process.env.CACHE_DURATION) || 300000;
/** * 获取 Telegram 频道内容 * 支持两种API方式:getChatHistory 和 getUpdates */async function fetchTelegramPosts() { const BOT_TOKEN = process.env.BOT_TOKEN; const CHANNEL_ID = process.env.CHANNEL_ID;
if (!BOT_TOKEN || !CHANNEL_ID) { throw new Error('请配置 BOT_TOKEN 和 CHANNEL_ID 环境变量'); }
try { console.log('正在从 Telegram 频道获取内容...');
// 方法1: 使用 getChatHistory APItry { const url = `https://api.telegram.org/bot${BOT_TOKEN}/getChatHistory`; const response = await axios.get(url, { params: { chat_id: CHANNEL_ID, limit: 20 }, timeout: 10000 });
if (response.data.ok && response.data.result) { return processBotAPIData(response.data.result); } } catch (error) { console.log('getChatHistory 失败:', error.message); }
// 方法2: 回退到 getUpdates APItry { const url = `https://api.telegram.org/bot${BOT_TOKEN}/getUpdates`; const response = await axios.get(url, { timeout: 10000 });
if (response.data.ok && response.data.result) { return processGetUpdatesData(response.data.result); } } catch (error) { console.log('getUpdates 失败:', error.message); }
throw new Error('所有 API 方法都失败了');
} catch (error) { console.error('获取 Telegram 内容失败:', error.message); throw error; } }
/** * 处理 getChatHistory 返回的数据 */function processBotAPIData(messages) { const posts = [];
messages.forEach((item) => { const message = item.message || item.channel_post; if (!message) return;
const post = { id: message.message_id, text: message.text || message.caption || '(无文字内容)', time: new Date(message.date * 1000).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }), image: null };
// 处理图片消息if (message.photo && message.photo.length > 0) { const photo = message.photo[message.photo.length - 1]; post.image = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/getFile?file_id=${photo.file_id}`; }
// 处理文档消息if (message.document) { post.document = message.document.file_name; }
posts.push(post); });
return posts.sort((a, b) => b.id - a.id); }
/** * 处理 getUpdates 返回的数据 */function processGetUpdatesData(updates) { const posts = [];
updates.forEach((update) => { const message = update.channel_post; if (!message) return;
const post = { id: message.message_id, text: message.text || message.caption || '(无文字内容)', time: new Date(message.date * 1000).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }), image: null };
// 标记图片消息if (message.photo && message.photo.length > 0) { post.hasImage = true; post.image = `图片消息 ID: ${message.message_id}`; }
posts.push(post); });
return posts.sort((a, b) => b.id - a.id); }
// API 路由 - 获取文章列表 app.get('/api/posts', async (req, res) => { try { const now = Date.now();
// 检查缓存是否过期if (now - lastFetchTime > CACHE_DURATION || cachedPosts.length === 0) { console.log('缓存过期,重新获取数据...'); cachedPosts = await fetchTelegramPosts(); lastFetchTime = now; }
res.json({ ok: true, channel: 'Kadriyeblog', posts: cachedPosts, count: cachedPosts.length, cached: lastFetchTime });
} catch (error) { console.error('API 错误:', error.message); res.status(500).json({ ok: false, error: error.message, posts: cachedPosts.length > 0 ? cachedPosts : [] }); } });
// 手动刷新缓存 app.post('/api/refresh', async (req, res) => { try { cachedPosts = await fetchTelegramPosts(); lastFetchTime = Date.now();
res.json({ ok: true, message: '缓存刷新成功', postsCount: cachedPosts.length }); } catch (error) { res.status(500).json({ ok: false, error: error.message }); } });
// 健康检查接口 app.get('/api/health', (req, res) => { res.json({ ok: true, status: 'running', cachedPosts: cachedPosts.length, lastFetch: new Date(lastFetchTime).toISOString(), environment: process.env.NODE_ENV }); });
// 提供前端页面 app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); });
// 启动服务器 app.listen(PORT, () => { console.log(`🚀 Telegram Blog 服务器已启动`); console.log(`📍 访问地址: <http://localhost>:${PORT}`); console.log(`📱 频道: Kadriyeblog`); console.log(`💾 环境: ${process.env.NODE_ENV || 'development'}`);
// 启动时预加载数据fetchTelegramPosts().then(posts => { cachedPosts = posts; lastFetchTime = Date.now(); console.log(`✅ 初始数据加载完成,共 ${posts.length} 篇文章`); }).catch(error => { console.log('❌ 初始数据加载失败:', error.message); }); });
// 优雅关闭处理 process.on('SIGINT', () => { console.log('\\n👋 正在关闭服务器...'); process.exit(0); });
|