index.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. require('dotenv').config();
  2. const express = require('express');
  3. const cors = require('cors');
  4. const path = require('path');
  5. const TelegramBot = require('node-telegram-bot-api');
  6. const fs = require('fs');
  7. const moment = require('moment');
  8. const { pool, testConnection } = require('./config/database');
  9. const initDatabase = require('./config/initDb');
  10. const Group = require('./models/Group');
  11. const Transaction = require('./models/Transaction');
  12. const app = express();
  13. // 初始化数据存储
  14. let data = {
  15. deposits: [], // 入款记录
  16. withdrawals: [], // 下发记录
  17. lastUpdate: null,
  18. allowedGroups: ['4754375683'] // 允许使用的群组ID
  19. };
  20. // 创建机器人实例
  21. const bot = new TelegramBot(process.env.BOT_TOKEN, { polling: true });
  22. // 中间件
  23. app.use(cors());
  24. app.use(express.json());
  25. app.use(express.static('views'));
  26. // 路由
  27. app.get('/', (req, res) => {
  28. res.sendFile(path.join(__dirname, 'views', 'login.html'));
  29. });
  30. app.use('/api/users', require('./routes/userRoutes'));
  31. app.use('/api/groups', require('./routes/groupRoutes'));
  32. app.use('/api/transactions', require('./routes/transactionRoutes'));
  33. // 检查群组权限
  34. function isGroupAllowed(chatId) {
  35. const chatIdStr = chatId.toString();
  36. return data.allowedGroups.includes(chatIdStr) ||
  37. data.allowedGroups.includes(chatIdStr.replace('-', ''));
  38. }
  39. // 检查是否是管理员
  40. function isAdmin(userId) {
  41. return process.env.ADMIN_IDS.split(',').includes(userId.toString());
  42. }
  43. // 处理消息发送
  44. async function sendMessage(chatId, text, options = {}) {
  45. try {
  46. // 如果包含内联键盘,验证URL
  47. if (options.reply_markup && options.reply_markup.inline_keyboard) {
  48. const keyboard = generateInlineKeyboard(chatId);
  49. if (!keyboard) {
  50. // 如果键盘无效,发送不带键盘的消息
  51. return await bot.sendMessage(chatId, text);
  52. }
  53. options.reply_markup = keyboard;
  54. }
  55. return await bot.sendMessage(chatId, text, options);
  56. } catch (error) {
  57. console.error('发送消息失败:', error);
  58. if (error.message.includes('bot was kicked from the group chat')) {
  59. const index = data.allowedGroups.indexOf(chatId.toString());
  60. if (index > -1) {
  61. data.allowedGroups.splice(index, 1);
  62. saveData();
  63. console.log(`群组 ${chatId} 已被移除出允许列表`);
  64. }
  65. }
  66. return null;
  67. }
  68. }
  69. // 处理快捷命令
  70. bot.on('message', async (msg) => {
  71. if (!isGroupAllowed(msg.chat.id)) return;
  72. const text = msg.text?.trim();
  73. if (!text) return;
  74. if (text.startsWith('+')) {
  75. const amount = parseFloat(text.substring(1));
  76. if (!isNaN(amount)) {
  77. const transactionData = {
  78. groupId: msg.chat.id.toString(),
  79. groupName: msg.chat.title || '未命名群组',
  80. amount: amount
  81. };
  82. try {
  83. const result = await Transaction.deposit(transactionData);
  84. if (result.success) {
  85. const billMessage = await generateBillMessage(msg.chat.id);
  86. if (billMessage) {
  87. await sendMessage(msg.chat.id, billMessage, {
  88. reply_markup: generateInlineKeyboard(msg.chat.id)
  89. });
  90. console.log(`入款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  91. } else {
  92. await sendMessage(msg.chat.id, '入款成功,但获取账单信息失败');
  93. console.log(`入款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  94. }
  95. } else {
  96. await sendMessage(msg.chat.id, result.message || '入款失败');
  97. console.log(`入款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  98. }
  99. } catch (error) {
  100. console.error('快捷入款失败:', error);
  101. await sendMessage(msg.chat.id, '记录入款失败,请稍后重试');
  102. }
  103. }
  104. } else if (text.startsWith('-')) {
  105. const amount = parseFloat(text.substring(1));
  106. if (!isNaN(amount)) {
  107. const transactionData = {
  108. groupId: msg.chat.id.toString(),
  109. groupName: msg.chat.title || '未命名群组',
  110. amount: amount
  111. };
  112. try {
  113. const result = await Transaction.withdrawal(transactionData);
  114. if (result.success) {
  115. const billMessage = await generateBillMessage(msg.chat.id);
  116. if (billMessage) {
  117. await sendMessage(msg.chat.id, billMessage, {
  118. reply_markup: generateInlineKeyboard(msg.chat.id)
  119. });
  120. console.log(`出款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  121. } else {
  122. await sendMessage(msg.chat.id, '出款成功,但获取账单信息失败');
  123. console.log(`出款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  124. }
  125. } else {
  126. await sendMessage(msg.chat.id, result.message || '出款失败');
  127. console.log(`出款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  128. }
  129. } catch (error) {
  130. console.error('快捷出款失败:', error);
  131. await sendMessage(msg.chat.id, '记录出款失败,请稍后重试');
  132. }
  133. }
  134. }
  135. });
  136. // 处理新成员加入
  137. bot.on('new_chat_members', async (msg) => {
  138. const chatId = msg.chat.id;
  139. const newMembers = msg.new_chat_members;
  140. for (const member of newMembers) {
  141. if (member.id === (await bot.getMe()).id) {
  142. // 机器人被添加到群组
  143. console.log(`机器人被添加到群组: ${chatId}`);
  144. // 检查群组是否在允许列表中
  145. const chatIdStr = chatId.toString();
  146. if (!data.allowedGroups.includes(chatIdStr)) {
  147. try {
  148. const groupData = {
  149. groupId: chatIdStr,
  150. groupName: msg.chat.title || '未命名群组',
  151. groupType: msg.chat.type === 'private' ? 'personal' : 'public',
  152. creatorId: msg.from.id.toString()
  153. };
  154. const id = await Group.create({
  155. groupId: groupData.groupId,
  156. groupName: groupData.groupName,
  157. creatorId: groupData.creatorId
  158. });
  159. const group = await Group.findById(id);
  160. if (group) {
  161. // 更新内存中的群组列表
  162. data.allowedGroups.push(chatIdStr);
  163. saveData();
  164. sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。');
  165. } else {
  166. sendMessage(chatId, '添加群组失败,请联系管理员。');
  167. }
  168. } catch (error) {
  169. console.error('创建群组失败:', error);
  170. sendMessage(chatId, '添加群组失败,请联系管理员。');
  171. }
  172. } else {
  173. sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。');
  174. }
  175. } else {
  176. // 其他新成员
  177. console.log(`新成员加入群组: ${member.username || member.first_name} (${member.id})`);
  178. sendMessage(chatId, `欢迎 ${member.username || member.first_name} 加入群组!`);
  179. }
  180. }
  181. });
  182. // 处理管理员命令
  183. bot.onText(/\/addgroup (.+)/, async (msg, match) => {
  184. if (!isAdmin(msg.from.id)) {
  185. sendMessage(msg.chat.id, '您没有权限执行此命令。');
  186. return;
  187. }
  188. const groupId = match[1].trim();
  189. if (!data.allowedGroups.includes(groupId)) {
  190. try {
  191. // 使用 createGroup 创建新群组
  192. const groupData = {
  193. groupId: groupId,
  194. groupName: '手动添加的群组',
  195. groupType: 'public',
  196. creatorId: msg.from.id.toString()
  197. };
  198. const result = await createGroup({ body: groupData });
  199. if (result) {
  200. data.allowedGroups.push(groupId);
  201. saveData();
  202. sendMessage(msg.chat.id, `群组 ${groupId} 已添加到允许列表。`);
  203. } else {
  204. sendMessage(msg.chat.id, '添加群组失败,请检查群组ID是否正确。');
  205. }
  206. } catch (error) {
  207. console.error('创建群组失败:', error);
  208. sendMessage(msg.chat.id, '添加群组失败,请稍后重试。');
  209. }
  210. } else {
  211. sendMessage(msg.chat.id, '该群组已在允许列表中。');
  212. }
  213. });
  214. bot.onText(/\/removegroup (.+)/, async (msg, match) => {
  215. if (!isAdmin(msg.from.id)) {
  216. sendMessage(msg.chat.id, '您没有权限执行此命令。');
  217. return;
  218. }
  219. const groupId = match[1].trim();
  220. try {
  221. // 使用 updateGroup 更新群组状态
  222. const result = await updateGroup({
  223. params: { id: groupId },
  224. body: { isActive: false }
  225. });
  226. if (result) {
  227. const index = data.allowedGroups.indexOf(groupId);
  228. if (index > -1) {
  229. data.allowedGroups.splice(index, 1);
  230. saveData();
  231. sendMessage(msg.chat.id, `群组 ${groupId} 已从允许列表中移除。`);
  232. } else {
  233. sendMessage(msg.chat.id, '该群组不在允许列表中。');
  234. }
  235. } else {
  236. sendMessage(msg.chat.id, '移除群组失败,请稍后重试。');
  237. }
  238. } catch (error) {
  239. console.error('更新群组状态失败:', error);
  240. sendMessage(msg.chat.id, '移除群组失败,请稍后重试。');
  241. }
  242. });
  243. bot.onText(/\/listgroups/, async (msg) => {
  244. if (!isAdmin(msg.from.id)) {
  245. sendMessage(msg.chat.id, '您没有权限执行此命令。');
  246. return;
  247. }
  248. try {
  249. const groups = await pool.query('SELECT group_id, group_name, group_type, is_active FROM groups WHERE is_active = 1');
  250. if (groups.length === 0) {
  251. sendMessage(msg.chat.id, '当前没有允许的群组。');
  252. return;
  253. }
  254. const groupsList = groups.map(group =>
  255. `ID: ${group.group_id}\n名称: ${group.group_name}\n类型: ${group.group_type}\n状态: ${group.is_active ? '启用' : '禁用'}`
  256. ).join('\n\n');
  257. sendMessage(msg.chat.id, `允许的群组列表:\n\n${groupsList}`);
  258. } catch (error) {
  259. console.error('获取群组列表失败:', error);
  260. sendMessage(msg.chat.id, '获取群组列表失败,请稍后重试。');
  261. }
  262. });
  263. // 处理入款命令
  264. bot.onText(/\/deposit (.+)/, async (msg, match) => {
  265. if (!isGroupAllowed(msg.chat.id)) {
  266. sendMessage(msg.chat.id, '该群组未授权使用此功能');
  267. return;
  268. }
  269. const amount = parseFloat(match[1]);
  270. if (isNaN(amount)) {
  271. sendMessage(msg.chat.id, '请输入有效的金额');
  272. return;
  273. }
  274. const transactionData = {
  275. groupId: msg.chat.id.toString(),
  276. groupName: msg.chat.title || '未命名群组',
  277. amount: amount
  278. };
  279. try {
  280. const result = await Transaction.deposit(transactionData);
  281. if (result.success) {
  282. const billMessage = await generateBillMessage(msg.chat.id);
  283. if (billMessage) {
  284. await sendMessage(msg.chat.id, billMessage, {
  285. reply_markup: generateInlineKeyboard(msg.chat.id)
  286. });
  287. console.log(`入款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  288. } else {
  289. await sendMessage(msg.chat.id, '入款成功,但获取账单信息失败');
  290. console.log(`入款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  291. }
  292. } else {
  293. await sendMessage(msg.chat.id, result.message || '入款失败');
  294. console.log(`入款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  295. }
  296. } catch (error) {
  297. console.error('记录入款失败:', error);
  298. await sendMessage(msg.chat.id, '记录入款失败,请稍后重试');
  299. }
  300. });
  301. // 处理下发命令
  302. bot.onText(/\/withdraw (.+)/, async (msg, match) => {
  303. if (!isGroupAllowed(msg.chat.id)) {
  304. sendMessage(msg.chat.id, '该群组未授权使用此功能');
  305. return;
  306. }
  307. const amount = parseFloat(match[1]);
  308. if (isNaN(amount)) {
  309. sendMessage(msg.chat.id, '请输入有效的金额');
  310. return;
  311. }
  312. const transactionData = {
  313. groupId: msg.chat.id.toString(),
  314. groupName: msg.chat.title || '未命名群组',
  315. amount: amount
  316. };
  317. try {
  318. const result = await Transaction.withdrawal(transactionData);
  319. if (result.success) {
  320. const billMessage = await generateBillMessage(msg.chat.id);
  321. if (billMessage) {
  322. await sendMessage(msg.chat.id, billMessage, {
  323. reply_markup: generateInlineKeyboard(msg.chat.id)
  324. });
  325. console.log(`出款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  326. } else {
  327. await sendMessage(msg.chat.id, '出款成功,但获取账单信息失败');
  328. console.log(`出款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  329. }
  330. } else {
  331. await sendMessage(msg.chat.id, result.message || '出款失败');
  332. console.log(`出款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  333. }
  334. } catch (error) {
  335. console.error('记录出款失败:', error);
  336. await sendMessage(msg.chat.id, '记录出款失败,请稍后重试');
  337. }
  338. });
  339. // 处理查看账单命令
  340. bot.onText(/\/bill/, async (msg) => {
  341. const billMessage = await generateBillMessage(msg.chat.id);
  342. sendMessage(msg.chat.id, billMessage, {
  343. reply_markup: generateInlineKeyboard(msg.chat.id)
  344. });
  345. });
  346. // 更新帮助命令
  347. bot.onText(/\/help/, (msg) => {
  348. const helpMessage = `
  349. 可用命令:
  350. /deposit <金额> - 记录入款
  351. /withdraw <金额> - 记录下发
  352. /bill - 查看当前账单
  353. /help - 显示此帮助信息
  354. 快捷命令:
  355. +<金额> - 快速记录入款(例如:+2000)
  356. -<金额> - 快速记录下发(例如:-2000)
  357. 管理员命令:
  358. /addgroup <群组ID> - 添加允许的群组
  359. /removegroup <群组ID> - 移除允许的群组
  360. /listgroups - 列出所有允许的群组
  361. `;
  362. sendMessage(msg.chat.id, helpMessage);
  363. });
  364. // 生成账单消息
  365. async function generateBillMessage(chatId) {
  366. try {
  367. // 获取最近的交易记录
  368. const [records] = await pool.query(`
  369. SELECT * FROM transactions
  370. WHERE group_id = ?
  371. ORDER BY time DESC
  372. LIMIT 10
  373. `, [chatId.toString()]);
  374. if (!records || records.length === 0) {
  375. return '暂无交易记录';
  376. }
  377. const deposits = records.filter(r => r.type === 'deposit');
  378. const withdrawals = records.filter(r => r.type === 'withdrawal');
  379. const totalDeposit = deposits.reduce((sum, d) => sum + parseFloat(d.amount), 0);
  380. const totalWithdrawal = withdrawals.reduce((sum, w) => sum + parseFloat(w.amount), 0);
  381. const depositFee = totalDeposit * (process.env.DEPOSIT_FEE_RATE || 0);
  382. const withdrawalFee = totalWithdrawal * (process.env.WITHDRAWAL_FEE_RATE || 0);
  383. const remaining = totalDeposit - depositFee - totalWithdrawal - withdrawalFee;
  384. let message = `入款(${deposits.length})笔:\n`;
  385. // 添加入款记录
  386. deposits.forEach(deposit => {
  387. message += `${moment(deposit.time).format('HH:mm:ss')} ${parseFloat(deposit.amount).toFixed(2)}\n`;
  388. });
  389. message += `\n下发(${withdrawals.length})笔:\n`;
  390. // 添加下发记录
  391. withdrawals.forEach(withdrawal => {
  392. message += `${moment(withdrawal.time).format('HH:mm:ss')} ${parseFloat(withdrawal.amount).toFixed(2)}\n`;
  393. });
  394. message += `\n总入款:${totalDeposit.toFixed(2)}\n`;
  395. message += `入款费率:${((process.env.DEPOSIT_FEE_RATE || 0) * 100).toFixed(1)}%\n`;
  396. message += `下发费率:${((process.env.WITHDRAWAL_FEE_RATE || 0) * 100).toFixed(1)}%\n`;
  397. message += `应下发:${(totalDeposit - depositFee).toFixed(2)}\n`;
  398. message += `总下发:${totalWithdrawal.toFixed(2)}\n`;
  399. message += `下发单笔附加费:0.0\n`;
  400. message += `单笔附费加总计:0.0\n`;
  401. message += `余:${remaining.toFixed(2)}`;
  402. return message;
  403. } catch (error) {
  404. console.error('生成账单消息失败:', error);
  405. return '获取账单信息失败,请稍后重试';
  406. }
  407. }
  408. // 生成内联键盘
  409. function generateInlineKeyboard(chatId) {
  410. const keyboard = {
  411. inline_keyboard: [
  412. [
  413. {
  414. text: '点击跳转完整账单',
  415. callback_data: `bill_page_${chatId}`
  416. }
  417. ],
  418. [
  419. {
  420. text: '24小时商务对接',
  421. callback_data: 'business_contact'
  422. }
  423. ]
  424. ]
  425. };
  426. return keyboard;
  427. }
  428. // 处理内联按钮回调
  429. bot.on('callback_query', async (callbackQuery) => {
  430. const chatId = callbackQuery.message.chat.id;
  431. const data = callbackQuery.data;
  432. try {
  433. if (data.startsWith('bill_page_')) {
  434. const groupId = data.split('_')[2];
  435. await bot.answerCallbackQuery(callbackQuery.id, {
  436. url: `${process.env.BILL_PAGE_BASE_URL}?groupId=${groupId}`
  437. });
  438. } else if (data === 'business_contact') {
  439. await bot.answerCallbackQuery(callbackQuery.id, {
  440. url: 'https://t.me/your_business_account'
  441. });
  442. }
  443. } catch (error) {
  444. console.error('处理内联按钮回调失败:', error);
  445. await bot.answerCallbackQuery(callbackQuery.id, {
  446. text: '操作失败,请稍后重试',
  447. show_alert: true
  448. });
  449. }
  450. });
  451. // 保存数据
  452. function saveData() {
  453. try {
  454. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  455. } catch (error) {
  456. console.error('Error saving data:', error);
  457. }
  458. }
  459. // 加载数据
  460. function loadData() {
  461. try {
  462. if (fs.existsSync(process.env.DB_FILE)) {
  463. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  464. data = { ...data, ...savedData };
  465. }
  466. } catch (error) {
  467. console.error('Error loading data:', error);
  468. }
  469. }
  470. // 测试数据库连接并初始化
  471. testConnection().then(() => {
  472. return initDatabase();
  473. }).then(() => {
  474. // 加载数据
  475. loadData();
  476. // 启动服务器
  477. const PORT = process.env.PORT || 3000;
  478. app.listen(PORT, () => {
  479. console.log(`服务器运行在端口 ${PORT}`);
  480. console.log('机器人已准备就绪!');
  481. });
  482. }).catch(error => {
  483. console.error('启动失败:', error);
  484. process.exit(1);
  485. });