index.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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 {
  9. pool,
  10. testConnection
  11. } = require('./config/database');
  12. const initDatabase = require('./config/initDb');
  13. const Group = require('./models/Group');
  14. const Transaction = require('./models/Transaction');
  15. // 日志格式化函数
  16. function formatLog(data) {
  17. const separator = '-'.repeat(30);
  18. let logMessage = `${separator}\n`;
  19. if (typeof data === 'object') {
  20. logMessage += Object.entries(data)
  21. .map(([key, value]) => `${key}: ${value}`)
  22. .join('\n');
  23. } else {
  24. logMessage += data;
  25. }
  26. logMessage += `\n${separator}\n`;
  27. return logMessage;
  28. }
  29. const app = express();
  30. // 初始化数据存储
  31. let data = {
  32. deposits: [], // 入款记录
  33. withdrawals: [], // 下发记录
  34. lastUpdate: null,
  35. allowedGroups: [] // 允许使用的群组ID
  36. };
  37. // 创建机器人实例
  38. const bot = new TelegramBot(process.env.BOT_TOKEN, {
  39. polling: true
  40. });
  41. // 中间件
  42. app.use(cors());
  43. app.use(express.json());
  44. app.use(express.urlencoded({ extended: true }));
  45. app.use('/admin/views', express.static(path.join(__dirname, 'views')));
  46. // 路由
  47. app.get('/', (req, res) => {
  48. res.sendFile(path.join(__dirname, 'views', 'login.html'));
  49. });
  50. app.use('/api/users', require('./routes/userRoutes'));
  51. app.use('/api/groups', require('./routes/groupRoutes'));
  52. app.use('/api/transactions', require('./routes/transactionRoutes'));
  53. app.use('/api/statistics', require('./routes/statisticsRoutes'));
  54. app.use('/api/settings', require('./routes/settingsRoutes'));
  55. // 检查群组权限
  56. function isGroupAllowed(chatId) {
  57. const chatIdStr = chatId.toString();
  58. return data.allowedGroups.includes(chatIdStr) ||
  59. data.allowedGroups.includes(chatIdStr.replace('-', ''));
  60. }
  61. // 前置处理
  62. // 检查用户是否有权限操作机器人
  63. async function checkUserPermission(chatId, userId) {
  64. try {
  65. const [group] = await pool.query(
  66. 'SELECT creator_id, COALESCE(operators, "[]") as operators FROM groups WHERE group_id = ?',
  67. [chatId.toString()]
  68. );
  69. if (!group || !group[0]) {
  70. console.log(`权限检查失败 - 群组不存在: ${chatId}`);
  71. return false;
  72. }
  73. const groupInfo = group[0];
  74. const userIdStr = userId.toString();
  75. const isCreator = groupInfo.creator_id === userIdStr;
  76. let operators = [];
  77. try {
  78. if (groupInfo.operators) {
  79. operators = JSON.parse(groupInfo.operators);
  80. if (!Array.isArray(operators)) {
  81. operators = [];
  82. }
  83. }
  84. } catch (e) {
  85. console.error('解析操作人列表失败:', e);
  86. operators = [];
  87. }
  88. const isOperator = operators.some(op => op.operator_id === userIdStr);
  89. // 只在权限检查失败时输出详细日志
  90. if (!isCreator && !isOperator) {
  91. console.log(`权限检查失败 - 用户ID: ${userIdStr}, 群组ID: ${chatId}, 创建者ID: ${groupInfo.creator_id}, 操作人数量: ${operators.length}`);
  92. }
  93. return isCreator || isOperator;
  94. } catch (error) {
  95. console.error('检查用户权限失败:', error);
  96. return false;
  97. }
  98. }
  99. // 处理消息发送
  100. async function sendMessage(chatId, text, options = {}) {
  101. try {
  102. // 如果包含内联键盘,验证URL
  103. if (options.reply_markup && options.reply_markup.inline_keyboard) {
  104. const keyboard = generateInlineKeyboard(chatId);
  105. if (!keyboard) {
  106. // 如果键盘无效,发送不带键盘的消息
  107. return await bot.sendMessage(chatId, text, {
  108. parse_mode: 'HTML'
  109. });
  110. }
  111. options.reply_markup = keyboard;
  112. }
  113. return await bot.sendMessage(chatId, text, {
  114. ...options,
  115. parse_mode: 'HTML'
  116. });
  117. } catch (error) {
  118. console.error('发送消息失败:', error);
  119. if (error.message.includes('bot was kicked from the group chat')) {
  120. const index = data.allowedGroups.indexOf(chatId.toString());
  121. if (index > -1) {
  122. data.allowedGroups.splice(index, 1);
  123. saveData();
  124. console.log(`群组 ${chatId} 已被移除出允许列表`);
  125. }
  126. }
  127. return null;
  128. }
  129. }
  130. // - 1.快捷命令
  131. bot.on('message', async (msg) => {
  132. if (!isGroupAllowed(msg.chat.id)) return;
  133. const text = msg.text?.trim();
  134. if (!text) return;
  135. // 0. 检查用户权限
  136. const hasPermission = await checkUserPermission(msg.chat.id, msg.from.id);
  137. if (!hasPermission) {
  138. // 如果不是创建人或操作人,直接返回
  139. return;
  140. }
  141. // 1. 处理入款命令
  142. if (text.startsWith('+')) {
  143. let amount, exchangeRate, feeRate;
  144. const parts = text.substring(1).split('/');
  145. amount = parseFloat(parts[0]);
  146. // 如果指定了汇率,则使用指定的汇率
  147. if (parts.length > 1) {
  148. exchangeRate = parseFloat(parts[1]);
  149. }
  150. // 如果指定了费率,则使用指定的费率
  151. if (parts.length > 2) {
  152. feeRate = parseFloat(parts[2]);
  153. }
  154. if (!isNaN(amount)) {
  155. const transactionData = {
  156. groupId: msg.chat.id.toString(),
  157. groupName: msg.chat.title || '未命名群组',
  158. amount: amount,
  159. type: 'deposit',
  160. exchangeRate: exchangeRate,
  161. feeRate: feeRate,
  162. operatorId: msg.from.id
  163. };
  164. // console.log(transactionData);
  165. try {
  166. const result = await Transaction.deposit(transactionData);
  167. if (result.success) {
  168. const billMessage = await generateBillMessage(msg.chat.id);
  169. if (billMessage) {
  170. await sendMessage(msg.chat.id, billMessage, {
  171. reply_markup: generateInlineKeyboard(msg.chat.id)
  172. });
  173. console.log(`入款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  174. } else {
  175. await sendMessage(msg.chat.id, '入款成功,但获取账单信息失败');
  176. console.log(`入款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  177. }
  178. } else {
  179. await sendMessage(msg.chat.id, result.message || '入款失败');
  180. console.log(`入款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  181. }
  182. } catch (error) {
  183. console.error('快捷入款失败:', error);
  184. await sendMessage(msg.chat.id, '记录入款失败,请稍后重试');
  185. }
  186. }
  187. }
  188. // 1.1 处理入款修正命令
  189. else if (text.startsWith('-') && !text.includes('下发')) {
  190. let amount, exchangeRate, feeRate;
  191. const parts = text.substring(1).split('/');
  192. amount = parseFloat(parts[0]);
  193. // 如果指定了汇率,则使用指定的汇率
  194. if (parts.length > 1) {
  195. exchangeRate = parseFloat(parts[1]);
  196. }
  197. // 如果指定了费率,则使用指定的费率
  198. if (parts.length > 2) {
  199. feeRate = parseFloat(parts[2]);
  200. }
  201. if (!isNaN(amount)) {
  202. const transactionData = {
  203. groupId: msg.chat.id.toString(),
  204. groupName: msg.chat.title || '未命名群组',
  205. amount: -amount,
  206. type: 'deposit',
  207. exchangeRate: exchangeRate,
  208. feeRate: feeRate,
  209. operatorId: msg.from.id
  210. };
  211. try {
  212. const result = await Transaction.deposit(transactionData);
  213. if (result.success) {
  214. const billMessage = await generateBillMessage(msg.chat.id);
  215. if (billMessage) {
  216. await sendMessage(msg.chat.id, billMessage, {
  217. reply_markup: generateInlineKeyboard(msg.chat.id)
  218. });
  219. console.log(`入款修正成功 - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  220. } else {
  221. await sendMessage(msg.chat.id, '入款修正成功,但获取账单信息失败');
  222. console.log(`入款修正成功(无账单) - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  223. }
  224. } else {
  225. await sendMessage(msg.chat.id, result.message || '入款修正失败');
  226. console.log(`入款修正失败 - 群组: ${msg.chat.title}, 金额: -${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  227. }
  228. } catch (error) {
  229. console.error('快捷入款修正失败:', error);
  230. await sendMessage(msg.chat.id, '记录入款修正失败,请稍后重试');
  231. }
  232. }
  233. }
  234. // 2. 处理回款命令
  235. else if (text.startsWith('下发')) {
  236. let amount, exchangeRate, feeRate;
  237. const parts = text.replace(/[^0-9./-]/g, '').split('/');
  238. amount = parseFloat(parts[0]);
  239. // 如果指定了汇率,则使用指定的汇率
  240. if (parts.length > 1) {
  241. exchangeRate = parseFloat(parts[1]);
  242. }
  243. // 如果指定了费率,则使用指定的费率
  244. if (parts.length > 2) {
  245. feeRate = parseFloat(parts[2]);
  246. }
  247. if (!isNaN(amount)) {
  248. const transactionData = {
  249. groupId: msg.chat.id.toString(),
  250. groupName: msg.chat.title || '未命名群组',
  251. amount: amount,
  252. type: 'withdrawal',
  253. exchangeRate: exchangeRate,
  254. feeRate: feeRate,
  255. operatorId: msg.from.id
  256. };
  257. try {
  258. const result = await Transaction.withdrawal(transactionData);
  259. if (result.success) {
  260. const billMessage = await generateBillMessage(msg.chat.id);
  261. if (billMessage) {
  262. await sendMessage(msg.chat.id, billMessage, {
  263. reply_markup: generateInlineKeyboard(msg.chat.id)
  264. });
  265. console.log(`回款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  266. } else {
  267. await sendMessage(msg.chat.id, '回款成功,但获取账单信息失败');
  268. console.log(`回款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  269. }
  270. } else {
  271. await sendMessage(msg.chat.id, result.message || '回款失败');
  272. console.log(`回款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  273. }
  274. } catch (error) {
  275. console.error('快捷回款失败:', error);
  276. await sendMessage(msg.chat.id, '记录回款失败,请稍后重试');
  277. }
  278. }
  279. }
  280. // 2.1 处理回款修正命令
  281. else if (text.startsWith('下发-')) {
  282. let amount, exchangeRate, feeRate;
  283. const parts = text.replace(/[^0-9./-]/g, '').split('/');
  284. amount = parseFloat(parts[0]);
  285. // 如果指定了汇率,则使用指定的汇率
  286. if (parts.length > 1) {
  287. exchangeRate = parseFloat(parts[1]);
  288. }
  289. // 如果指定了费率,则使用指定的费率
  290. if (parts.length > 2) {
  291. feeRate = parseFloat(parts[2]);
  292. }
  293. if (!isNaN(amount)) {
  294. const transactionData = {
  295. groupId: msg.chat.id.toString(),
  296. groupName: msg.chat.title || '未命名群组',
  297. amount: -amount,
  298. type: 'withdrawal',
  299. exchangeRate: exchangeRate,
  300. feeRate: feeRate,
  301. operatorId: msg.from.id
  302. };
  303. try {
  304. const result = await Transaction.withdrawal(transactionData);
  305. if (result.success) {
  306. const billMessage = await generateBillMessage(msg.chat.id);
  307. if (billMessage) {
  308. await sendMessage(msg.chat.id, billMessage, {
  309. reply_markup: generateInlineKeyboard(msg.chat.id)
  310. });
  311. console.log(`回款修正成功 - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  312. } else {
  313. await sendMessage(msg.chat.id, '回款修正成功,但获取账单信息失败');
  314. console.log(`回款修正成功(无账单) - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  315. }
  316. } else {
  317. await sendMessage(msg.chat.id, result.message || '回款修正失败');
  318. console.log(`回款修正失败 - 群组: ${msg.chat.title}, 金额: -${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  319. }
  320. } catch (error) {
  321. console.error('快捷回款修正失败:', error);
  322. await sendMessage(msg.chat.id, '记录回款修正失败,请稍后重试');
  323. }
  324. }
  325. }
  326. // 3. 处理设置费率命令
  327. else if (text.startsWith('设置费率')) {
  328. const feeRate = parseFloat(text.replace('设置费率', '').trim());
  329. if (!isNaN(feeRate) && feeRate >= 0 && feeRate <= 100) {
  330. try {
  331. // 更新群组的入款和出款费率
  332. await pool.query(`
  333. UPDATE groups
  334. SET in_fee_rate = ?,
  335. out_fee_rate = ?,
  336. updated_at = CURRENT_TIMESTAMP
  337. WHERE group_id = ?
  338. `, [feeRate, feeRate, msg.chat.id.toString()]);
  339. await sendMessage(msg.chat.id, `费率${feeRate}%已设置成功`);
  340. console.log(`费率设置成功 - 群组: ${msg.chat.title}, 费率: ${feeRate}%, 时间: ${new Date().toLocaleString()}`);
  341. } catch (error) {
  342. console.error('设置费率失败:', error);
  343. await sendMessage(msg.chat.id, '设置费率失败,请稍后重试');
  344. }
  345. } else {
  346. await sendMessage(msg.chat.id, '费率设置失败,请输入0-100之间的数字');
  347. }
  348. }
  349. // 4. 处理设置汇率命令
  350. else if (text.startsWith('设置汇率')) {
  351. const exchangeRate = parseFloat(text.replace('设置汇率', '').trim());
  352. if (!isNaN(exchangeRate) && exchangeRate > 0) {
  353. try {
  354. // 更新群组的入款和出款汇率
  355. await pool.query(`
  356. UPDATE groups
  357. SET in_exchange_rate = ?,
  358. out_exchange_rate = ?,
  359. updated_at = CURRENT_TIMESTAMP
  360. WHERE group_id = ?
  361. `, [exchangeRate, exchangeRate, msg.chat.id.toString()]);
  362. await sendMessage(msg.chat.id, `汇率${exchangeRate}已设置成功`);
  363. console.log(`汇率设置成功 - 群组: ${msg.chat.title}, 汇率: ${exchangeRate}, 时间: ${new Date().toLocaleString()}`);
  364. } catch (error) {
  365. console.error('设置汇率失败:', error);
  366. await sendMessage(msg.chat.id, '设置汇率失败,请稍后重试');
  367. }
  368. } else {
  369. await sendMessage(msg.chat.id, '汇率设置失败,请输入大于0的数字');
  370. }
  371. }
  372. // 5. 处理设置操作人命令
  373. else if (text.startsWith('设置操作人')) {
  374. try {
  375. const groupId = msg.chat.id.toString();
  376. const mentionedUser = msg.entities?.find(e => e.type === 'mention');
  377. if (!mentionedUser) {
  378. // 如果没有@用户,回复原消息并提示设置用户名
  379. await bot.sendMessage(msg.chat.id, '请设置您的Telegram用户名后再试', {
  380. reply_to_message_id: msg.message_id
  381. });
  382. return;
  383. }
  384. // 获取被@的用户名
  385. const username = text.slice(mentionedUser.offset + 1, mentionedUser.offset + mentionedUser.length);
  386. // 获取群组信息
  387. const [group] = await pool.query(
  388. 'SELECT creator_id, COALESCE(operators, "[]") as operators FROM groups WHERE group_id = ?',
  389. [groupId]
  390. );
  391. if (!group || !group[0]) {
  392. await sendMessage(msg.chat.id, '群组信息不存在');
  393. return;
  394. }
  395. const groupInfo = group[0];
  396. const userId = msg.from.id.toString();
  397. // 检查操作权限(群组创建者或现有操作人)
  398. const isCreator = groupInfo.creator_id === userId;
  399. let operators = [];
  400. try {
  401. if (groupInfo.operators) {
  402. operators = JSON.parse(groupInfo.operators);
  403. if (!Array.isArray(operators)) {
  404. operators = [];
  405. }
  406. }
  407. } catch (e) {
  408. console.error('解析操作人列表失败:', e);
  409. operators = [];
  410. }
  411. const isOperator = operators.some(op => op.operator_id === userId);
  412. if (!isCreator && !isOperator) {
  413. await sendMessage(msg.chat.id, '您没有权限设置操作人');
  414. return;
  415. }
  416. // 获取被@用户的ID
  417. const [user] = await pool.query(
  418. 'SELECT id FROM users WHERE username = ?',
  419. [username]
  420. );
  421. let newOperatorId;
  422. if (!user || !user[0]) {
  423. // 如果用户不存在,创建新用户
  424. try {
  425. const [result] = await pool.query(
  426. 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)',
  427. [username, '', 'user']
  428. );
  429. newOperatorId = result.insertId.toString();
  430. console.log(`创建新用户成功 - 用户名: ${username}, ID: ${newOperatorId}`);
  431. } catch (error) {
  432. console.error('创建新用户失败:', error);
  433. await sendMessage(msg.chat.id, '创建用户失败,请稍后重试');
  434. return;
  435. }
  436. } else {
  437. newOperatorId = user[0].id.toString();
  438. }
  439. // 检查是否已经是操作人
  440. if (operators.some(op => op.operator_id === newOperatorId)) {
  441. await sendMessage(msg.chat.id, '该用户已经是操作人');
  442. return;
  443. }
  444. // 添加新操作人
  445. operators.push({
  446. operator_id: newOperatorId,
  447. operator_username: username,
  448. added_by: userId,
  449. added_at: new Date().toISOString()
  450. });
  451. // 更新群组
  452. await pool.query(
  453. 'UPDATE groups SET operators = ? WHERE group_id = ?',
  454. [JSON.stringify(operators), groupId]
  455. );
  456. await sendMessage(msg.chat.id, `已成功设置 @${username} 为操作人`);
  457. console.log(`设置操作人成功 - 群组: ${msg.chat.title}, 新操作人: ${username}, 设置者: ${msg.from.username || msg.from.first_name}, 时间: ${new Date().toLocaleString()}`);
  458. } catch (error) {
  459. console.error('设置操作人失败:', error);
  460. if (error.code === 'ER_BAD_FIELD_ERROR') {
  461. await sendMessage(msg.chat.id, '系统正在升级,请稍后再试');
  462. } else {
  463. await sendMessage(msg.chat.id, '设置操作人失败,请稍后重试');
  464. }
  465. }
  466. }
  467. // 6. 处理TRX地址
  468. else if (/^T[A-Za-z0-9]{33}$/.test(text)) {
  469. try {
  470. const groupId = msg.chat.id.toString();
  471. // 检查地址是否已存在
  472. const [existingAddress] = await pool.query(
  473. 'SELECT * FROM trx_addresses WHERE address = ? AND group_id = ?',
  474. [text, groupId]
  475. );
  476. if (existingAddress && existingAddress.length > 0) {
  477. // 更新使用次数和最后出现时间
  478. await pool.query(`
  479. UPDATE trx_addresses
  480. SET usage_count = usage_count + 1,
  481. last_seen_time = CURRENT_TIMESTAMP
  482. WHERE address = ? AND group_id = ?
  483. `, [text, groupId]);
  484. const newCount = existingAddress[0].usage_count + 1;
  485. await sendMessage(msg.chat.id, `此地址累计发送第${newCount}次`);
  486. console.log(`TRX地址使用次数更新 - 群组: ${msg.chat.title}, 地址: ${text}, 次数: ${newCount}, 时间: ${new Date().toLocaleString()}`);
  487. } else {
  488. // 插入新地址记录
  489. await pool.query(`
  490. INSERT INTO trx_addresses (address, group_id)
  491. VALUES (?, ?)
  492. `, [text, groupId]);
  493. await sendMessage(msg.chat.id, '此地址累计发送第1次');
  494. console.log(`新TRX地址记录 - 群组: ${msg.chat.title}, 地址: ${text}, 时间: ${new Date().toLocaleString()}`);
  495. }
  496. } catch (error) {
  497. console.error('处理TRX地址失败:', error);
  498. await sendMessage(msg.chat.id, '处理地址失败,请稍后重试');
  499. }
  500. }
  501. });
  502. // - 2.查看账单
  503. // 生成账单消息
  504. async function generateBillMessage(chatId) {
  505. try {
  506. // 获取群组的最后加入时间和费率信息
  507. const [groupInfo] = await pool.query(
  508. 'SELECT last_join_time, in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate FROM groups WHERE group_id = ?',
  509. [chatId.toString()]
  510. );
  511. if (!groupInfo || groupInfo.length === 0) {
  512. return '暂无交易记录';
  513. }
  514. const lastJoinTime = groupInfo[0].last_join_time;
  515. const inFeeRate = parseFloat(groupInfo[0].in_fee_rate) || 0;
  516. const inExchangeRate = parseFloat(groupInfo[0].in_exchange_rate) || 0;
  517. const outFeeRate = parseFloat(groupInfo[0].out_fee_rate) || 0;
  518. const outExchangeRate = parseFloat(groupInfo[0].out_exchange_rate) || 0;
  519. // 获取机器人加入后的交易记录
  520. const [records] = await pool.query(`
  521. SELECT t.*,
  522. COALESCE(t.fee_rate, g.in_fee_rate) as fee_rate,
  523. COALESCE(t.exchange_rate, g.in_exchange_rate) as exchange_rate
  524. FROM transactions t
  525. LEFT JOIN groups g ON t.group_id = g.group_id
  526. WHERE t.group_id = ?
  527. AND DATE(t.time) = CURDATE()
  528. ORDER BY t.time DESC
  529. `, [chatId.toString()]);
  530. if (!records || records.length === 0) {
  531. return '暂无交易记录';
  532. }
  533. const deposits = records.filter(r => r.type === 'deposit');
  534. const withdrawals = records.filter(r => r.type === 'withdrawal');
  535. const totalDeposit = deposits.reduce((sum, d) => sum + parseFloat(d.amount), 0);
  536. const totalWithdrawal = withdrawals.reduce((sum, w) => sum + parseFloat(w.amount), 0);
  537. const depositFee = totalDeposit * (inFeeRate / 100);
  538. const withdrawalFee = totalWithdrawal * (outFeeRate / 100);
  539. const remaining = totalDeposit - depositFee - totalWithdrawal - withdrawalFee;
  540. const remainingU = (remaining / inExchangeRate).toFixed(2);
  541. // 获取当前日期
  542. const today = new Date();
  543. const version = 'v29';
  544. const dateStr = today.toISOString().split('T')[0].replace(/-/g, '-');
  545. let message = `当前版本:<b>${dateStr}:${version}</b>\n\n`;
  546. // 添加入款记录
  547. if (deposits.length > 0) {
  548. message += `<b>入款笔数</b>:<code>${deposits.length}</code>\n`;
  549. deposits.forEach(deposit => {
  550. message += `<code>${moment(deposit.time).format('HH:mm:ss')} ${parseFloat(deposit.amount).toFixed(2)}</code>\n`;
  551. });
  552. message += '\n';
  553. } else {
  554. message += `<b>入款笔数</b>:<code>0</code>\n\n`;
  555. }
  556. // 添加出款记录
  557. if (withdrawals.length > 0) {
  558. message += `<b>出款笔数</b>:<code>${withdrawals.length}</code>\n`;
  559. withdrawals.forEach(withdrawal => {
  560. message += `<code>${moment(withdrawal.time).format('HH:mm:ss')} ${parseFloat(withdrawal.amount).toFixed(2)}</code>\n`;
  561. });
  562. message += '\n';
  563. } else {
  564. message += `<b>出款笔数</b>:<code>0</code>\n\n`;
  565. }
  566. // 添加费率信息
  567. message += `<b>入款费率</b>:<code>${inFeeRate}%</code>\n`;
  568. message += `<b>入款汇率</b>:<code>${inExchangeRate}</code>\n`;
  569. message += `<b>入款总额</b>:<code>${totalDeposit.toFixed(2)}</code>\n`;
  570. message += `<b>入款合计</b>:<code>${(totalDeposit - depositFee).toFixed(2)}|${((totalDeposit - depositFee) / inExchangeRate).toFixed(2)}U</code>\n\n`;
  571. message += `<b>出款费率</b>:<code>${outFeeRate}%</code>\n`;
  572. message += `<b>出款汇率</b>:<code>${outExchangeRate}</code>\n`;
  573. message += `<b>出款总额</b>:<code>${totalWithdrawal.toFixed(2)}</code>\n`;
  574. message += `<b>出款合计</b>:<code>${(totalWithdrawal - withdrawalFee).toFixed(2)}|${((totalWithdrawal - withdrawalFee) / outExchangeRate).toFixed(2)}U</code>\n\n`;
  575. // 添加余额信息
  576. message += `<b>应下发</b>:<code>${remainingU}U</code>\n`;
  577. message += `<b>已下发</b>:<code>${(totalWithdrawal / outExchangeRate).toFixed(2)}U</code>\n`;
  578. message += `<b>未下发</b>:<code>${(remainingU - (totalWithdrawal / outExchangeRate)).toFixed(2)}U</code>`;
  579. return message;
  580. } catch (error) {
  581. console.error(formatLog('生成账单消息失败', error));
  582. return '获取账单信息失败,请稍后重试';
  583. }
  584. }
  585. // 生成内联键盘
  586. function generateInlineKeyboard(chatId) {
  587. const keyboard = {
  588. inline_keyboard: [
  589. [{
  590. text: '点击跳转完整账单',
  591. callback_data: `bill_page_${chatId}`
  592. }],
  593. [{
  594. text: '24小时商务对接',
  595. callback_data: 'business_contact'
  596. }]
  597. ]
  598. };
  599. return keyboard;
  600. }
  601. // 处理内联按钮回调
  602. bot.on('callback_query', async (callbackQuery) => {
  603. const chatId = callbackQuery.message.chat.id;
  604. const data = callbackQuery.data;
  605. try {
  606. if (data.startsWith('bill_page_')) {
  607. const groupId = data.split('_')[2];
  608. await bot.answerCallbackQuery(callbackQuery.id, {
  609. url: 'https://google.com'
  610. });
  611. } else if (data === 'business_contact') {
  612. await bot.answerCallbackQuery(callbackQuery.id, {
  613. url: 'https://t.me/your_business_account'
  614. });
  615. }
  616. } catch (error) {
  617. console.error(formatLog('处理内联按钮回调失败', error));
  618. await bot.answerCallbackQuery(callbackQuery.id, {
  619. text: '操作失败,请稍后重试',
  620. show_alert: true
  621. });
  622. }
  623. });
  624. bot.onText(/\/bill/, async (msg) => {
  625. const billMessage = await generateBillMessage(msg.chat.id);
  626. sendMessage(msg.chat.id, billMessage, {
  627. reply_markup: generateInlineKeyboard(msg.chat.id)
  628. });
  629. });
  630. // - 3.帮助命令
  631. bot.onText(/\/help/, (msg) => {
  632. const helpMessage = `
  633. 🤖 <b>机器人使用指南</b>
  634. <b>📝 快捷命令</b>
  635. • <code>+数字</code> 快速记录入款
  636. • <code>-数字</code> 快速记录入款修正
  637. • <code>下发数字</code> 快速记录下发
  638. • <code>下发-数字</code> 快速记录下发修正
  639. <b>⚙️ 设置命令</b>
  640. • <code>设置费率数字</code> 设置费率
  641. • <code>设置汇率数字</code> 设置汇率
  642. • <code>设置操作人@用户名</code> 设置群组操作人
  643. <b>📊 查询命令</b>
  644. • <code>/bill</code> 查看当前账单
  645. • <code>/help</code> 显示此帮助信息
  646. <b>💡 使用提示</b>
  647. • 所有金额输入请使用数字
  648. • 账单信息实时更新
  649. • 如需帮助请联系管理员
  650. `;
  651. sendMessage(msg.chat.id, helpMessage);
  652. });
  653. // - 4.群组信息更新
  654. // 机器人被添加到群组
  655. bot.on('new_chat_members', async (msg) => {
  656. // 获取机器人ID
  657. const botInfo = await bot.getMe();
  658. // console.log('机器人信息:', botInfo);
  659. // 检查是否机器人被添加
  660. const botMember = msg.new_chat_members.find(member => member.id === botInfo.id);
  661. if (!botMember) {
  662. console.log('机器人未被添加,忽略事件');
  663. return;
  664. }
  665. try {
  666. const chatId = msg.chat.id.toString();
  667. const chatTitle = msg.chat.title || '未命名群组';
  668. const creatorId = msg.from.id.toString();
  669. console.log('开始处理群组初始化:', {
  670. chatId,
  671. chatTitle,
  672. creatorId
  673. });
  674. // 检查群组是否已存在
  675. const [existingGroup] = await pool.query(
  676. 'SELECT * FROM groups WHERE group_id = ?',
  677. [chatId]
  678. );
  679. if (!existingGroup || existingGroup.length === 0) {
  680. // 创建新群组记录
  681. await pool.query(`
  682. INSERT INTO groups (
  683. group_id,
  684. group_name,
  685. creator_id,
  686. in_fee_rate,
  687. out_fee_rate,
  688. in_exchange_rate,
  689. out_exchange_rate,
  690. last_join_time,
  691. created_at,
  692. updated_at,
  693. operators
  694. ) VALUES (?, ?, ?, 0, 0, 1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '[]')
  695. `, [chatId, chatTitle, creatorId]);
  696. // 将群组添加到允许列表
  697. if (!data.allowedGroups.includes(chatId)) {
  698. data.allowedGroups.push(chatId);
  699. saveData();
  700. }
  701. // 发送欢迎消息
  702. await sendMessage(msg.chat.id, `感谢您添加我进入群组!\n\n我已初始化群组账单系统,您可以使用以下命令开始使用:\n\n• <code>/help</code> 查看使用指南\n• <code>/bill</code> 查看当前账单`);
  703. console.log(`新群组初始化成功 - 群组: ${chatTitle}, ID: ${chatId}, 创建者: ${creatorId}, 时间: ${new Date().toLocaleString()}`);
  704. } else {
  705. // 更新群组信息
  706. await pool.query(`
  707. UPDATE groups
  708. SET group_name = ?,
  709. last_join_time = CURRENT_TIMESTAMP,
  710. updated_at = CURRENT_TIMESTAMP
  711. WHERE group_id = ?
  712. `, [chatTitle, chatId]);
  713. // 确保群组在允许列表中
  714. if (!data.allowedGroups.includes(chatId)) {
  715. data.allowedGroups.push(chatId);
  716. saveData();
  717. }
  718. await sendMessage(msg.chat.id, `我已重新加入群组!\n\n您可以使用 <code>/help</code> 查看使用指南`);
  719. console.log(`群组信息更新成功 - 群组: ${chatTitle}, ID: ${chatId}, 时间: ${new Date().toLocaleString()}`);
  720. }
  721. } catch (error) {
  722. console.error('处理新群组失败:', error);
  723. await sendMessage(msg.chat.id, '初始化群组失败,请稍后重试');
  724. }
  725. });
  726. // 保存数据
  727. function saveData() {
  728. try {
  729. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  730. } catch (error) {
  731. console.error(formatLog('Error saving data', error));
  732. }
  733. }
  734. // 加载数据
  735. function loadData() {
  736. try {
  737. if (fs.existsSync(process.env.DB_FILE)) {
  738. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  739. data = {
  740. ...data,
  741. ...savedData
  742. };
  743. }
  744. } catch (error) {
  745. console.error(formatLog('Error loading data', error));
  746. }
  747. }
  748. // 测试数据库连接并初始化
  749. testConnection().then(() => {
  750. return initDatabase();
  751. }).then(() => {
  752. // 加载数据
  753. loadData();
  754. // 启动服务器
  755. const PORT = process.env.PORT || 3000;
  756. app.listen(PORT, () => {
  757. console.log(formatLog({
  758. PORT: PORT
  759. }));
  760. console.log('机器人已准备就绪!');
  761. });
  762. }).catch(error => {
  763. console.error(formatLog('启动失败', error));
  764. process.exit(1);
  765. });
  766. // 导入公共路由
  767. const publicRoutes = require('./routes/public');
  768. // 注册公共路由
  769. app.use('/api/public', publicRoutes);
  770. // 错误处理中间件
  771. app.use((err, req, res, next) => {
  772. console.error(err.stack);
  773. res.status(500).json({ message: '服务器错误' });
  774. });
  775. // 404 处理
  776. app.use((req, res) => {
  777. res.status(404).json({ message: '未找到请求的资源' });
  778. });
  779. module.exports = app;