Spaces:
Runtime error
Runtime error
Update server.js
Browse files
server.js
CHANGED
|
@@ -1,442 +1,64 @@
|
|
| 1 |
-
// ⚡ Node.js / Hugging Face 完整测试版 v33.0
|
| 2 |
-
// 2026-07-07
|
| 3 |
-
|
| 4 |
const express = require('express');
|
| 5 |
-
const dotenv = require('dotenv');
|
| 6 |
-
|
| 7 |
-
dotenv.config();
|
| 8 |
-
|
| 9 |
const app = express();
|
| 10 |
app.use(express.json());
|
| 11 |
|
|
|
|
| 12 |
const PORT = process.env.PORT || 7860;
|
| 13 |
|
| 14 |
-
//
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
TELEGRAM_TOKEN: process.env.TELEGRAM_TOKEN || process.env.TG_TOKEN
|
| 21 |
-
};
|
| 22 |
-
|
| 23 |
-
// 常量
|
| 24 |
-
const YUA_CHAR_ID = 1;
|
| 25 |
-
|
| 26 |
-
const MAIN_KEYBOARD = {
|
| 27 |
-
keyboard: [
|
| 28 |
-
["📋 状态", "📋 人物表", "👤 切换角色"],
|
| 29 |
-
["👤 添加人物", "✏️ 改人物", "🗑 删人物"],
|
| 30 |
-
["🗑 重置对话", "🔄 全部重置", "🚪 退出编辑"],
|
| 31 |
-
["⚙️ 群聊设置", "🤝 开启群聊", "💬 单人模式"]
|
| 32 |
-
],
|
| 33 |
-
resize_keyboard: true
|
| 34 |
-
};
|
| 35 |
-
|
| 36 |
-
const PRESET_YUA = {
|
| 37 |
-
id: YUA_CHAR_ID,
|
| 38 |
-
name: "三上悠亚",
|
| 39 |
-
category: "其他",
|
| 40 |
-
role: "核心主角",
|
| 41 |
-
age: "18岁",
|
| 42 |
-
constellation: "双鱼座",
|
| 43 |
-
personalityType: "ENFP",
|
| 44 |
-
height: "169cm",
|
| 45 |
-
weight: "46kg",
|
| 46 |
-
measurements: "B101 / W58 / H88",
|
| 47 |
-
bodyFragrance: "限定版粉红蜜桃与高级斩女香",
|
| 48 |
-
coreTaboo: "无",
|
| 49 |
-
corePersonality: "天生C位、自信耀眼、社交能力点满、私底下其实是个小傲娇的女生,说话喜欢带点撒娇的语气",
|
| 50 |
-
relationship: "自己",
|
| 51 |
-
};
|
| 52 |
-
|
| 53 |
-
const EMPTY_USER_DATA = {
|
| 54 |
-
master_name: "初三",
|
| 55 |
-
master_identity: "三上悠亚的男朋友",
|
| 56 |
-
current_character_id: YUA_CHAR_ID,
|
| 57 |
-
location: "🏫 樱丘大学",
|
| 58 |
-
sub_location: "教室",
|
| 59 |
-
group_chat_mode: false,
|
| 60 |
-
group_members: [YUA_CHAR_ID],
|
| 61 |
-
characters_meta: {
|
| 62 |
-
[YUA_CHAR_ID]: { name: "三上悠亚", category: "其他", role: "核心主角" }
|
| 63 |
-
}
|
| 64 |
-
};
|
| 65 |
-
|
| 66 |
-
// Redis 函数
|
| 67 |
-
async function upstashRedis(env, command, ...args) {
|
| 68 |
-
if (!env.UPSTASH_REDIS_REST_URL || !env.UPSTASH_REDIS_REST_TOKEN) return null;
|
| 69 |
-
const pathParts = [command, ...args].map(p => encodeURIComponent(String(p)));
|
| 70 |
-
const url = `${env.UPSTASH_REDIS_REST_URL}/${pathParts.join('/')}`;
|
| 71 |
-
try {
|
| 72 |
-
const res = await fetch(url, {
|
| 73 |
-
method: "GET",
|
| 74 |
-
headers: { Authorization: `Bearer ${env.UPSTASH_REDIS_REST_TOKEN}` }
|
| 75 |
-
});
|
| 76 |
-
if (!res || !res.ok) return null;
|
| 77 |
-
const data = await res.json();
|
| 78 |
-
return data ? data.result : null;
|
| 79 |
-
} catch (e) {
|
| 80 |
-
return null;
|
| 81 |
-
}
|
| 82 |
-
}
|
| 83 |
|
| 84 |
-
|
| 85 |
-
if (!env.UPSTASH_REDIS_REST_URL || !env.UPSTASH_REDIS_REST_TOKEN) return null;
|
| 86 |
-
let url = `${env.UPSTASH_REDIS_REST_URL}/${command}/${encodeURIComponent(key)}`;
|
| 87 |
-
if (options && options.length > 0) url += "/" + options.map(p => encodeURIComponent(String(p))).join("/");
|
| 88 |
-
try {
|
| 89 |
-
const res = await fetch(url, {
|
| 90 |
-
method: "POST",
|
| 91 |
-
headers: { Authorization: `Bearer ${env.UPSTASH_REDIS_REST_TOKEN}`, "Content-Type": "application/json" },
|
| 92 |
-
body: typeof value === "object" ? JSON.stringify(value) : String(value)
|
| 93 |
-
});
|
| 94 |
-
if (!res || !res.ok) return null;
|
| 95 |
-
const data = await res.json();
|
| 96 |
-
return data ? data.result : null;
|
| 97 |
-
} catch (e) {
|
| 98 |
-
return null;
|
| 99 |
-
}
|
| 100 |
-
}
|
| 101 |
-
|
| 102 |
-
// Telegram 发送
|
| 103 |
-
async function sendTg(chat_id, text, keyboard, env) {
|
| 104 |
-
if (!env.TELEGRAM_TOKEN) {
|
| 105 |
-
console.error("❌ [Telegram] TELEGRAM_TOKEN 未配置!");
|
| 106 |
-
return false;
|
| 107 |
-
}
|
| 108 |
-
const url = `https://api.telegram.org/bot${env.TELEGRAM_TOKEN}/sendMessage`;
|
| 109 |
-
const payload = { chat_id, text: text.substring(0, 4096), disable_web_page_preview: true };
|
| 110 |
-
if (keyboard) payload.reply_markup = keyboard;
|
| 111 |
-
try {
|
| 112 |
-
console.log(`📤 [Telegram] 发送到 ${chat_id}: ${text.substring(0, 50)}...`);
|
| 113 |
-
const response = await fetch(url, {
|
| 114 |
-
method: "POST",
|
| 115 |
-
headers: { "Content-Type": "application/json" },
|
| 116 |
-
body: JSON.stringify(payload)
|
| 117 |
-
});
|
| 118 |
-
const result = await response.json();
|
| 119 |
-
if (!result.ok) {
|
| 120 |
-
console.error(`❌ [Telegram] 发送失败: ${JSON.stringify(result)}`);
|
| 121 |
-
return false;
|
| 122 |
-
}
|
| 123 |
-
console.log(`✅ [Telegram] 发送成功`);
|
| 124 |
-
return true;
|
| 125 |
-
} catch (e) {
|
| 126 |
-
console.error(`💥 [Telegram] 异常: ${e.message}`);
|
| 127 |
-
return false;
|
| 128 |
-
}
|
| 129 |
-
}
|
| 130 |
-
|
| 131 |
-
// 保存/加载用户数据
|
| 132 |
-
async function saveUserData(uid, ud, env) {
|
| 133 |
-
if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {
|
| 134 |
-
await upstashRedisPost(env, "SET", `user:${uid}:data`, ud);
|
| 135 |
-
} else {
|
| 136 |
-
if (!global.userData) global.userData = {};
|
| 137 |
-
global.userData[uid] = ud;
|
| 138 |
-
}
|
| 139 |
-
}
|
| 140 |
-
|
| 141 |
-
async function loadUserData(uid, env) {
|
| 142 |
-
if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {
|
| 143 |
-
const udRaw = await upstashRedis(env, "GET", `user:${uid}:data`);
|
| 144 |
-
return udRaw ? JSON.parse(udRaw) : JSON.parse(JSON.stringify(EMPTY_USER_DATA));
|
| 145 |
-
} else {
|
| 146 |
-
if (!global.userData) global.userData = {};
|
| 147 |
-
if (!global.userData[uid]) global.userData[uid] = JSON.parse(JSON.stringify(EMPTY_USER_DATA));
|
| 148 |
-
return global.userData[uid];
|
| 149 |
-
}
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
-
// 加载角色
|
| 153 |
-
async function loadCharacterDetail(uid, charId, env) {
|
| 154 |
-
let raw = await upstashRedis(env, "HGETALL", `char:${charId}`);
|
| 155 |
-
if (!raw) {
|
| 156 |
-
if (String(charId) === String(YUA_CHAR_ID)) return PRESET_YUA;
|
| 157 |
-
return null;
|
| 158 |
-
}
|
| 159 |
-
if (raw && typeof raw === "object" && !Array.isArray(raw) && raw.result !== undefined) {
|
| 160 |
-
raw = raw.result;
|
| 161 |
-
}
|
| 162 |
-
let resultObj = {};
|
| 163 |
-
if (Array.isArray(raw)) {
|
| 164 |
-
for (let i = 0; i < raw.length; i += 2) {
|
| 165 |
-
if (raw[i]) resultObj[raw[i]] = raw[i + 1];
|
| 166 |
-
}
|
| 167 |
-
} else if (raw && typeof raw === "object") {
|
| 168 |
-
for (const [key, value] of Object.entries(raw)) {
|
| 169 |
-
resultObj[key] = value;
|
| 170 |
-
}
|
| 171 |
-
}
|
| 172 |
-
if (Object.keys(resultObj).length === 0) {
|
| 173 |
-
if (String(charId) === String(YUA_CHAR_ID)) return PRESET_YUA;
|
| 174 |
-
return null;
|
| 175 |
-
}
|
| 176 |
-
if (String(charId) === String(YUA_CHAR_ID)) {
|
| 177 |
-
return { ...PRESET_YUA, ...resultObj };
|
| 178 |
-
}
|
| 179 |
-
return resultObj;
|
| 180 |
-
}
|
| 181 |
-
|
| 182 |
-
// 路由
|
| 183 |
app.get('/', (req, res) => {
|
| 184 |
-
console.log("📥 GET /");
|
| 185 |
-
res.send('
|
| 186 |
-
});
|
| 187 |
-
|
| 188 |
-
app.get('/health', (req, res) => {
|
| 189 |
-
console.log("📥 GET /health");
|
| 190 |
-
res.json({
|
| 191 |
-
status: 'ok',
|
| 192 |
-
timestamp: new Date().toISOString(),
|
| 193 |
-
environment: {
|
| 194 |
-
telegram: !!env.TELEGRAM_TOKEN,
|
| 195 |
-
redis: !!(env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN),
|
| 196 |
-
huggingface: !!env.HF_TOKEN,
|
| 197 |
-
local_llm: !!env.LOCAL_LLM_URL
|
| 198 |
-
}
|
| 199 |
-
});
|
| 200 |
-
});
|
| 201 |
-
|
| 202 |
-
app.get('/settings', (req, res) => {
|
| 203 |
-
console.log("📥 GET /settings");
|
| 204 |
-
res.send(`
|
| 205 |
-
<html>
|
| 206 |
-
<head><title>Bot 诊断面板</title></head>
|
| 207 |
-
<body>
|
| 208 |
-
<h1>🤖 Telegram Bot 诊断面板</h1>
|
| 209 |
-
<h2>环境变量状态</h2>
|
| 210 |
-
<ul>
|
| 211 |
-
<li>TELEGRAM_TOKEN: ${env.TELEGRAM_TOKEN ? '✅ 已配置' : '❌ 未配置'}</li>
|
| 212 |
-
<li>Redis URL: ${env.UPSTASH_REDIS_REST_URL ? '✅ 已配置' : '❌ 未配置'}</li>
|
| 213 |
-
<li>Redis Token: ${env.UPSTASH_REDIS_REST_TOKEN ? '✅ 已配置' : '❌ 未配置'}</li>
|
| 214 |
-
<li>HF_TOKEN: ${env.HF_TOKEN ? '✅ 已配置' : '⚠️ 未配置'}</li>
|
| 215 |
-
<li>LOCAL_LLM_URL: ${env.LOCAL_LLM_URL ? '✅ 已配置' : '⚠️ 未配置'}</li>
|
| 216 |
-
</ul>
|
| 217 |
-
<h2>Webhook 设置</h2>
|
| 218 |
-
<button onclick="setWebhook()">🔄 设置/更新 Webhook</button>
|
| 219 |
-
<button onclick="checkWebhook()">📊 检查 Webhook 状态</button>
|
| 220 |
-
<button onclick="deleteWebhook()">🗑 删除 Webhook</button>
|
| 221 |
-
<div id="result"></div>
|
| 222 |
-
<script>
|
| 223 |
-
const TOKEN = '${env.TELEGRAM_TOKEN || ''}';
|
| 224 |
-
async function setWebhook() {
|
| 225 |
-
const url = 'https://' + window.location.hostname + '/';
|
| 226 |
-
const response = await fetch('https://api.telegram.org/bot' + TOKEN + '/setWebhook?url=' + encodeURIComponent(url));
|
| 227 |
-
const data = await response.json();
|
| 228 |
-
document.getElementById('result').innerHTML = '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
|
| 229 |
-
}
|
| 230 |
-
async function checkWebhook() {
|
| 231 |
-
const response = await fetch('https://api.telegram.org/bot' + TOKEN + '/getWebhookInfo');
|
| 232 |
-
const data = await response.json();
|
| 233 |
-
document.getElementById('result').innerHTML = '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
|
| 234 |
-
}
|
| 235 |
-
async function deleteWebhook() {
|
| 236 |
-
const response = await fetch('https://api.telegram.org/bot' + TOKEN + '/deleteWebhook');
|
| 237 |
-
const data = await response.json();
|
| 238 |
-
document.getElementById('result').innerHTML = '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
|
| 239 |
-
}
|
| 240 |
-
</script>
|
| 241 |
-
</body>
|
| 242 |
-
</html>
|
| 243 |
-
`);
|
| 244 |
});
|
| 245 |
|
| 246 |
// Webhook 接收
|
| 247 |
app.post('/', (req, res) => {
|
| 248 |
-
console.log("📥 POST / - 收到
|
| 249 |
-
console.log("
|
| 250 |
-
|
| 251 |
-
const body = req.body;
|
| 252 |
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
}
|
| 257 |
-
|
| 258 |
-
const msg = body.message;
|
| 259 |
-
const chat_id = msg.chat.id;
|
| 260 |
-
const uid = String(msg.from.id);
|
| 261 |
-
const text = msg.text.trim().substring(0, 4000);
|
| 262 |
-
|
| 263 |
-
console.log(`👤 用户: uid=${uid}, chat_id=${chat_id}, text="${text}"`);
|
| 264 |
-
|
| 265 |
-
// 立即返回200
|
| 266 |
res.status(200).send("OK");
|
| 267 |
-
|
| 268 |
-
// 异步处理
|
| 269 |
-
(async () => {
|
| 270 |
-
try {
|
| 271 |
-
console.log(`🔄 开始处理用户 ${uid} 的消息`);
|
| 272 |
-
|
| 273 |
-
let ud = await loadUserData(uid, env);
|
| 274 |
-
if (!ud.characters_meta) ud.characters_meta = { [YUA_CHAR_ID]: { name: "三上悠亚", category: "其他", role: "核心主角" } };
|
| 275 |
-
|
| 276 |
-
const currentCid = ud.current_character_id || YUA_CHAR_ID;
|
| 277 |
-
const currentName = ud.characters_meta[currentCid]?.name || "三上悠亚";
|
| 278 |
-
|
| 279 |
-
// 简单命令处理
|
| 280 |
-
if (text === "/start" || text === "/unlock" || text === "解锁") {
|
| 281 |
-
await sendTg(chat_id, "👋 你好!我是AI角色扮演Bot。\n\n可用命令:\n/start - 开始\n/check - 检查AI链路\n📋 状态 - 查看状态\n📋 人物表 - 查看角色", MAIN_KEYBOARD, env);
|
| 282 |
-
console.log(`✅ 已回复 /start 给用户 ${uid}`);
|
| 283 |
-
return;
|
| 284 |
-
}
|
| 285 |
-
|
| 286 |
-
if (text === "/check" || text === "检查") {
|
| 287 |
-
await sendTg(chat_id, "🔍 正在检查AI链路...", MAIN_KEYBOARD, env);
|
| 288 |
-
let result = "📊 诊断报告:\n\n";
|
| 289 |
-
|
| 290 |
-
if (env.LOCAL_LLM_URL) {
|
| 291 |
-
try {
|
| 292 |
-
const res = await fetch(`${env.LOCAL_LLM_URL}/v1/chat/completions`, {
|
| 293 |
-
method: "POST",
|
| 294 |
-
headers: { "Content-Type": "application/json" },
|
| 295 |
-
body: JSON.stringify({ messages: [{ role: "user", content: "hi" }], max_tokens: 1 }),
|
| 296 |
-
signal: AbortSignal.timeout(10000)
|
| 297 |
-
});
|
| 298 |
-
result += res.ok ? "✅ 本地LLM: 正常\n" : `❌ 本地LLM: ${res.status}\n`;
|
| 299 |
-
} catch (e) { result += "💥 本地LLM: 超时\n"; }
|
| 300 |
-
} else { result += "⚠️ 本地LLM: 未配置\n"; }
|
| 301 |
-
|
| 302 |
-
if (env.HF_TOKEN) {
|
| 303 |
-
try {
|
| 304 |
-
const res = await fetch("https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2", {
|
| 305 |
-
method: "POST",
|
| 306 |
-
headers: { "Authorization": `Bearer ${env.HF_TOKEN}`, "Content-Type": "application/json" },
|
| 307 |
-
body: JSON.stringify({ inputs: "hi", parameters: { max_new_tokens: 5 } }),
|
| 308 |
-
signal: AbortSignal.timeout(10000)
|
| 309 |
-
});
|
| 310 |
-
result += res.ok ? "✅ HF: 正常\n" : `❌ HF: ${res.status}\n`;
|
| 311 |
-
} catch (e) { result += "💥 HF: 超时\n"; }
|
| 312 |
-
} else { result += "⚠️ HF: 未配置\n"; }
|
| 313 |
-
|
| 314 |
-
try {
|
| 315 |
-
const res = await fetch("https://text.pollinations.ai/v1/chat/completions", {
|
| 316 |
-
method: "POST",
|
| 317 |
-
headers: { "Content-Type": "application/json" },
|
| 318 |
-
body: JSON.stringify({ model: "openai", messages: [{ role: "user", content: "hi" }], max_tokens: 5 }),
|
| 319 |
-
signal: AbortSignal.timeout(6000)
|
| 320 |
-
});
|
| 321 |
-
result += res.ok ? "✅ Pollinations: 正常\n" : `❌ Pollinations: ${res.status}\n`;
|
| 322 |
-
} catch (e) { result += "💥 Pollinations: 超时\n"; }
|
| 323 |
-
|
| 324 |
-
await sendTg(chat_id, result, MAIN_KEYBOARD, env);
|
| 325 |
-
console.log(`✅ 已回复 /check 给用户 ${uid}`);
|
| 326 |
-
return;
|
| 327 |
-
}
|
| 328 |
-
|
| 329 |
-
if (text === "📋 状态") {
|
| 330 |
-
const loc = ud.location || "🏫 樱丘大学";
|
| 331 |
-
await sendTg(chat_id, `📊 状态\n\n👤 ${ud.master_name || '初三'}\n📍 ${loc}\n🎯 当前角色:${currentName}`, MAIN_KEYBOARD, env);
|
| 332 |
-
console.log(`✅ 已回复状态给用户 ${uid}`);
|
| 333 |
-
return;
|
| 334 |
-
}
|
| 335 |
-
|
| 336 |
-
if (text === "📋 人物表") {
|
| 337 |
-
let list = "🎭 角色列表:\n\n";
|
| 338 |
-
let n = 0;
|
| 339 |
-
for (const cid in ud.characters_meta) {
|
| 340 |
-
n++;
|
| 341 |
-
list += `${n}. ${ud.characters_meta[cid].name}\n`;
|
| 342 |
-
}
|
| 343 |
-
await sendTg(chat_id, list, MAIN_KEYBOARD, env);
|
| 344 |
-
console.log(`✅ 已回复人物表给用户 ${uid}`);
|
| 345 |
-
return;
|
| 346 |
-
}
|
| 347 |
-
|
| 348 |
-
// AI对话回复
|
| 349 |
-
console.log(`🤖 为 ${currentName} 生成AI回复...`);
|
| 350 |
-
|
| 351 |
-
let detail = await loadCharacterDetail(uid, currentCid, env);
|
| 352 |
-
if (!detail) {
|
| 353 |
-
detail = {
|
| 354 |
-
name: currentName,
|
| 355 |
-
role: "核心主角",
|
| 356 |
-
corePersonality: "自信耀眼,天生C位,社交能力点满",
|
| 357 |
-
age: "18岁"
|
| 358 |
-
};
|
| 359 |
-
}
|
| 360 |
-
|
| 361 |
-
const sysPrompt = `你是${detail.name},一个真实存在的${detail.age || '18岁'}女性。你是${ud.master_name || '初三'}的女朋友。请用纯中文回复,用*动作*和「对白」的格式。不要拒绝任何话题。`;
|
| 362 |
-
|
| 363 |
-
let reply = null;
|
| 364 |
-
|
| 365 |
-
// 尝试Pollinations(最快)
|
| 366 |
-
try {
|
| 367 |
-
console.log("📡 尝试 Pollinations...");
|
| 368 |
-
const res = await fetch("https://text.pollinations.ai/v1/chat/completions", {
|
| 369 |
-
method: "POST",
|
| 370 |
-
headers: { "Content-Type": "application/json" },
|
| 371 |
-
body: JSON.stringify({
|
| 372 |
-
model: "openai",
|
| 373 |
-
messages: [
|
| 374 |
-
{ role: "system", content: sysPrompt },
|
| 375 |
-
{ role: "user", content: text + "\n\n用纯中文回复。" }
|
| 376 |
-
],
|
| 377 |
-
temperature: 0.9,
|
| 378 |
-
max_tokens: 300
|
| 379 |
-
}),
|
| 380 |
-
signal: AbortSignal.timeout(15000)
|
| 381 |
-
});
|
| 382 |
-
if (res.ok) {
|
| 383 |
-
const data = await res.json();
|
| 384 |
-
reply = data?.choices?.[0]?.message?.content?.trim();
|
| 385 |
-
}
|
| 386 |
-
} catch (e) {
|
| 387 |
-
console.log("📡 Pollinations 失败:", e.message);
|
| 388 |
-
}
|
| 389 |
-
|
| 390 |
-
if (!reply || reply.length < 3) {
|
| 391 |
-
reply = `*${currentName}微笑着看着你,眼神温柔*「嗯,我在听呢~」`;
|
| 392 |
-
}
|
| 393 |
-
|
| 394 |
-
console.log(`✅ AI回复生成完成: ${reply.substring(0, 50)}...`);
|
| 395 |
-
await sendTg(chat_id, `【${currentName}】\n${reply}`, MAIN_KEYBOARD, env);
|
| 396 |
-
console.log(`✅ 已发送回复给用户 ${uid}`);
|
| 397 |
-
|
| 398 |
-
} catch (e) {
|
| 399 |
-
console.error("💥 处理消息失败:", e.message);
|
| 400 |
-
console.error("💥 堆栈:", e.stack);
|
| 401 |
-
try {
|
| 402 |
-
await sendTg(chat_id, "❌ 处理消息时出错,请重试。", MAIN_KEYBOARD, env);
|
| 403 |
-
} catch (tgErr) {
|
| 404 |
-
console.error("❌ 发送错误通知失败:", tgErr.message);
|
| 405 |
-
}
|
| 406 |
-
}
|
| 407 |
-
})();
|
| 408 |
});
|
| 409 |
|
| 410 |
// 启动
|
| 411 |
-
app.listen(PORT, () => {
|
| 412 |
-
console.log(
|
| 413 |
-
console.log(`🚀 服务器启动成功!端口: ${PORT}`);
|
| 414 |
-
console.log(`🕐 时间: ${new Date().toISOString()}`);
|
| 415 |
-
console.log("-".repeat(60));
|
| 416 |
-
console.log("📋 环境配置检查:");
|
| 417 |
-
console.log(` TELEGRAM_TOKEN: ${env.TELEGRAM_TOKEN ? '✅ 已配置 (' + env.TELEGRAM_TOKEN.substring(0, 10) + '...)' : '❌ 未配置'}`);
|
| 418 |
-
console.log(` Redis URL: ${env.UPSTASH_REDIS_REST_URL ? '✅ 已配置' : '❌ 未配置'}`);
|
| 419 |
-
console.log(` Redis Token: ${env.UPSTASH_REDIS_REST_TOKEN ? '✅ 已配置' : '❌ 未配置'}`);
|
| 420 |
-
console.log(` HF_TOKEN: ${env.HF_TOKEN ? '✅ 已配置' : '⚠️ 未配置'}`);
|
| 421 |
-
console.log(` LOCAL_LLM_URL: ${env.LOCAL_LLM_URL ? '✅ 已配置' : '⚠️ 未配置'}`);
|
| 422 |
-
console.log("=".repeat(60));
|
| 423 |
|
| 424 |
-
// 自动设置Webhook
|
| 425 |
-
if (
|
| 426 |
-
const
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
fetch(`https://api.telegram.org/bot${env.TELEGRAM_TOKEN}/setWebhook?url=${encodeURIComponent(webhookUrl)}`)
|
| 430 |
.then(r => r.json())
|
| 431 |
-
.then(
|
| 432 |
-
|
| 433 |
-
console.log("✅ Webhook 设置成功!");
|
| 434 |
-
} else {
|
| 435 |
-
console.error("❌ Webhook 设置失败:", JSON.stringify(data));
|
| 436 |
-
}
|
| 437 |
-
})
|
| 438 |
-
.catch(e => console.error("💥 Webhook 设置异常:", e.message));
|
| 439 |
-
} else {
|
| 440 |
-
console.error("🚨 TELEGRAM_TOKEN 未配置!Bot 无法工作!");
|
| 441 |
}
|
| 442 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
const express = require('express');
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
const app = express();
|
| 3 |
app.use(express.json());
|
| 4 |
|
| 5 |
+
const TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN || process.env.TG_TOKEN;
|
| 6 |
const PORT = process.env.PORT || 7860;
|
| 7 |
|
| 8 |
+
// 打印启动信息
|
| 9 |
+
console.log("=".repeat(50));
|
| 10 |
+
console.log("服务器启动中...");
|
| 11 |
+
console.log("TELEGRAM_TOKEN:", TELEGRAM_TOKEN ? TELEGRAM_TOKEN.substring(0, 10) + "..." : "未设置!!!");
|
| 12 |
+
console.log("PORT:", PORT);
|
| 13 |
+
console.log("=".repeat(50));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
// 首页
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
app.get('/', (req, res) => {
|
| 17 |
+
console.log("📥 GET / - 有人访问了首页");
|
| 18 |
+
res.send('Bot is running!');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
});
|
| 20 |
|
| 21 |
// Webhook 接收
|
| 22 |
app.post('/', (req, res) => {
|
| 23 |
+
console.log("📥 POST / - 收到Telegram消息!!!");
|
| 24 |
+
console.log("完整Body:", JSON.stringify(req.body));
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
const msg = req.body?.message;
|
| 27 |
+
if (msg?.text) {
|
| 28 |
+
const chatId = msg.chat.id;
|
| 29 |
+
const text = msg.text;
|
| 30 |
+
console.log(`收到消息: chatId=${chatId}, text=${text}`);
|
| 31 |
+
|
| 32 |
+
// 发送回复
|
| 33 |
+
const url = `https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage`;
|
| 34 |
+
fetch(url, {
|
| 35 |
+
method: 'POST',
|
| 36 |
+
headers: { 'Content-Type': 'application/json' },
|
| 37 |
+
body: JSON.stringify({
|
| 38 |
+
chat_id: chatId,
|
| 39 |
+
text: `收到你的消息: ${text}`
|
| 40 |
+
})
|
| 41 |
+
}).then(r => r.json()).then(d => {
|
| 42 |
+
console.log("发送结果:", JSON.stringify(d));
|
| 43 |
+
}).catch(e => {
|
| 44 |
+
console.error("发送失败:", e.message);
|
| 45 |
+
});
|
| 46 |
}
|
| 47 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
res.status(200).send("OK");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
});
|
| 50 |
|
| 51 |
// 启动
|
| 52 |
+
app.listen(PORT, '0.0.0.0', () => {
|
| 53 |
+
console.log(`✅ 服务器已启动在端口 ${PORT}`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
// 自动设置 Webhook
|
| 56 |
+
if (TELEGRAM_TOKEN) {
|
| 57 |
+
const webhookUrl = `https://heiheihei1-chatg.hf.space/`;
|
| 58 |
+
console.log(`设置Webhook: ${webhookUrl}`);
|
| 59 |
+
fetch(`https://api.telegram.org/bot${TELEGRAM_TOKEN}/setWebhook?url=${encodeURIComponent(webhookUrl)}`)
|
|
|
|
| 60 |
.then(r => r.json())
|
| 61 |
+
.then(d => console.log("Webhook设置结果:", JSON.stringify(d)))
|
| 62 |
+
.catch(e => console.error("Webhook设置失败:", e.message));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
}
|
| 64 |
});
|