index.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. async function handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup) {
  656. try {
  657. // 获取群组链接
  658. const chatInfo = await bot.getChat(chatId);
  659. const groupInfo = {
  660. ID: chatId,
  661. 名称: msg.chat.title || '未命名群组',
  662. 类型: chatType,
  663. 状态: existingGroup ? '重新激活' : '已激活',
  664. 群组链接: chatInfo.invite_link || '未设置',
  665. 更新时间: new Date().toLocaleString()
  666. };
  667. console.log(formatLog({
  668. 操作: '处理机器人添加',
  669. 群组信息: groupInfo
  670. }));
  671. // 如果群组不存在,创建新群组
  672. if (!existingGroup) {
  673. const groupData = {
  674. groupId: chatIdStr,
  675. groupName: msg.chat.title || '未命名群组',
  676. groupType: chatType === 'private' ? 'personal' : chatType,
  677. creatorId: msg.from.id.toString()
  678. };
  679. try {
  680. // 检查群组是否已经存在
  681. const [existingGroupCheck] = await pool.query(
  682. 'SELECT * FROM groups WHERE group_id = ?',
  683. [chatIdStr]
  684. );
  685. if (existingGroupCheck && existingGroupCheck.length > 0) {
  686. console.log(formatLog({
  687. 操作: '群组已存在,更新状态',
  688. 群组ID: chatIdStr
  689. }));
  690. // 更新现有群组状态
  691. await pool.query(`
  692. UPDATE groups
  693. SET is_active = true,
  694. group_name = ?,
  695. group_type = ?,
  696. last_join_time = CURRENT_TIMESTAMP
  697. WHERE group_id = ?
  698. `, [
  699. groupData.groupName,
  700. groupData.groupType,
  701. chatIdStr
  702. ]);
  703. } else {
  704. // 创建新群组
  705. await pool.query(`
  706. INSERT INTO groups
  707. (group_id, group_name, group_type, creator_id, is_active, last_join_time,
  708. in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate, operators)
  709. VALUES (?, ?, ?, ?, true, CURRENT_TIMESTAMP, 0.00, 1.0000, 0.00, 1.0000, '[]')
  710. `, [
  711. groupData.groupId,
  712. groupData.groupName,
  713. groupData.groupType,
  714. groupData.creatorId
  715. ]);
  716. }
  717. // 更新内存中的群组列表
  718. if (!data.allowedGroups.includes(chatIdStr)) {
  719. data.allowedGroups.push(chatIdStr);
  720. saveData();
  721. }
  722. console.log(formatLog({
  723. 操作: '群组添加成功',
  724. 群组ID: chatIdStr,
  725. 群组名称: groupData.groupName
  726. }));
  727. } catch (error) {
  728. console.error(formatLog({
  729. 错误: '创建群组失败',
  730. 详情: error.message,
  731. 群组ID: groupData.groupId
  732. }));
  733. // 检查是否是重复添加导致的错误
  734. if (error.code === 'ER_DUP_ENTRY') {
  735. console.log(formatLog({
  736. 操作: '检测到重复添加',
  737. 群组ID: chatIdStr
  738. }));
  739. return;
  740. }
  741. await bot.sendMessage(chatId, '添加群组失败,请联系管理员。', {
  742. parse_mode: 'HTML'
  743. });
  744. }
  745. }
  746. } catch (error) {
  747. console.error(formatLog({
  748. 错误: '处理群组添加失败',
  749. 详情: error.message
  750. }));
  751. await sendMessage(chatId, '添加群组失败,请联系管理员。');
  752. }
  753. }
  754. // 处理群组信息更新
  755. async function handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus, newType) {
  756. const connection = await pool.getConnection();
  757. await connection.beginTransaction();
  758. try {
  759. // 更新群组ID和类型
  760. const oldGroupId = existingGroup.group_id;
  761. // 如果群组ID发生变化,更新所有相关记录
  762. if (existingGroup.group_type != newType) {
  763. console.log(formatLog({
  764. 操作: '群组类型更新',
  765. 名称: msg.chat.title || existingGroup.group_name,
  766. 旧ID: oldGroupId,
  767. 新ID: chatIdStr,
  768. 旧类型: existingGroup.group_type,
  769. 新类型: newType,
  770. 状态: newStatus !== 'kicked' && newStatus !== 'left' ? '活跃' : '已移除'
  771. }));
  772. // 开始事务
  773. await connection.beginTransaction();
  774. try {
  775. // 检查目标ID是否已存在
  776. const [existingTargetGroup] = await connection.query(
  777. 'SELECT * FROM groups WHERE group_id = ?',
  778. [chatIdStr]
  779. );
  780. if (existingTargetGroup && existingTargetGroup.length > 0) {
  781. // 更新交易记录
  782. await connection.query(`
  783. UPDATE transactions
  784. SET group_id = ?
  785. WHERE group_id = ?
  786. `, [chatIdStr, oldGroupId]);
  787. // 更新资金记录
  788. await connection.query(`
  789. UPDATE money_records
  790. SET group_id = ?
  791. WHERE group_id = ?
  792. `, [chatIdStr, oldGroupId]);
  793. // 删除旧群组记录
  794. await connection.query(
  795. 'DELETE FROM groups WHERE group_id = ?',
  796. [oldGroupId]
  797. );
  798. // 更新目标群组信息
  799. await connection.query(`
  800. UPDATE groups
  801. SET group_type = ?,
  802. group_name = ?,
  803. is_active = ?,
  804. updated_at = CURRENT_TIMESTAMP
  805. WHERE group_id = ?
  806. `, [
  807. newType,
  808. msg.chat.title || existingGroup.group_name,
  809. newStatus !== 'kicked' && newStatus !== 'left',
  810. chatIdStr
  811. ]);
  812. } else {
  813. // 如果目标ID不存在,执行正常的更新操作
  814. // 先删除旧记录
  815. await connection.query(
  816. 'DELETE FROM groups WHERE group_id = ?',
  817. [oldGroupId]
  818. );
  819. // 插入新记录
  820. await connection.query(`
  821. INSERT INTO groups
  822. (group_id, group_name, group_type, creator_id, is_active, last_join_time)
  823. VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
  824. `, [
  825. chatIdStr,
  826. msg.chat.title || existingGroup.group_name,
  827. newType,
  828. existingGroup.creator_id,
  829. newStatus !== 'kicked' && newStatus !== 'left'
  830. ]);
  831. // 更新交易记录
  832. await connection.query(`
  833. UPDATE transactions
  834. SET group_id = ?
  835. WHERE group_id = ?
  836. `, [chatIdStr, oldGroupId]);
  837. // 更新资金记录
  838. await connection.query(`
  839. UPDATE money_records
  840. SET group_id = ?
  841. WHERE group_id = ?
  842. `, [chatIdStr, oldGroupId]);
  843. }
  844. // 提交事务
  845. await connection.commit();
  846. // 更新内存中的群组列表
  847. const index = data.allowedGroups.indexOf(oldGroupId);
  848. if (index > -1) {
  849. if (newStatus === 'kicked' || newStatus === 'left') {
  850. data.allowedGroups.splice(index, 1);
  851. } else {
  852. data.allowedGroups[index] = chatIdStr;
  853. }
  854. saveData();
  855. }
  856. } catch (error) {
  857. // 回滚事务
  858. await connection.rollback();
  859. console.error(formatLog('更新群组信息失败', error));
  860. throw error;
  861. }
  862. } else {
  863. // 如果ID没有变化,只更新其他信息
  864. await connection.query(`
  865. UPDATE groups
  866. SET group_type = ?,
  867. group_name = ?,
  868. is_active = ?,
  869. updated_at = CURRENT_TIMESTAMP
  870. WHERE group_id = ?
  871. `, [
  872. newType,
  873. msg.chat.title || existingGroup.group_name,
  874. newStatus !== 'kicked' && newStatus !== 'left',
  875. chatIdStr
  876. ]);
  877. }
  878. await connection.commit();
  879. console.log('【群组状态变更】');
  880. console.log(formatLog({
  881. ID: oldGroupId + ' -> ' + chatIdStr,
  882. type: existingGroup.group_type + ' -> ' + newType,
  883. name: existingGroup.group_name + ' -> ' + msg.chat.title || existingGroup.group_name,
  884. status: newStatus === 'kicked' || newStatus === 'left' ? '已移除' : '活跃'
  885. }));
  886. } catch (error) {
  887. await connection.rollback();
  888. console.error(formatLog({
  889. 错误: '更新群组信息失败',
  890. 详情: error.message
  891. }));
  892. throw error;
  893. } finally {
  894. connection.release();
  895. }
  896. }
  897. // 处理群组状态变更
  898. bot.on('my_chat_member', async (msg) => {
  899. try {
  900. const chatId = msg.chat.id;
  901. const newStatus = msg.new_chat_member.status;
  902. const oldStatus = msg.old_chat_member.status;
  903. const chatType = msg.chat.type;
  904. const chatIdStr = chatId.toString();
  905. console.log(formatLog({
  906. 操作: '收到群组状态变更',
  907. 群组ID: chatIdStr,
  908. 群组名称: msg.chat.title,
  909. 旧状态: oldStatus,
  910. 新状态: newStatus,
  911. 群组类型: chatType
  912. }));
  913. // 定义群组类型
  914. const newType = chatType === 'private' ? 'personal' :
  915. chatType === 'supergroup' ? 'supergroup' : 'group';
  916. // 查找群组,同时检查新旧ID
  917. const existingGroup = await Group.findByGroupId(chatIdStr) ||
  918. await Group.findByGroupId(chatIdStr.replace('-', ''));
  919. // 如果是机器人首次被添加到群组(从非成员变为成员)
  920. if (oldStatus === 'left' && newStatus === 'member') {
  921. // 如果群组已存在且处于活跃状态,则发送欢迎消息
  922. if (existingGroup && existingGroup.is_active) {
  923. console.log(formatLog({
  924. 操作: '机器人重新加入群组',
  925. 群组ID: chatIdStr,
  926. 群组名称: msg.chat.title || existingGroup.group_name
  927. }));
  928. try {
  929. // 发送欢迎消息
  930. await bot.sendMessage(chatId, '感谢重新添加我为群组成员!', {
  931. parse_mode: 'HTML'
  932. });
  933. // 发送账单消息
  934. const billMessage = await generateBillMessage(chatId);
  935. if (billMessage) {
  936. await bot.sendMessage(chatId, billMessage, {
  937. parse_mode: 'HTML',
  938. reply_markup: generateInlineKeyboard(chatId)
  939. });
  940. }
  941. } catch (error) {
  942. console.error(formatLog({
  943. 错误: '发送消息失败',
  944. 详情: error.message,
  945. 群组ID: chatIdStr
  946. }));
  947. }
  948. return;
  949. }
  950. // 检查邀请者是否已存在于用户表中
  951. const [existingUser] = await pool.query(
  952. 'SELECT * FROM users WHERE id = ?',
  953. [msg.from.id]
  954. );
  955. // 如果用户不存在,则创建新用户
  956. if (!existingUser || existingUser.length === 0) {
  957. // 生成唯一的用户名
  958. const username = msg.from.username || `user_${msg.from.id}`;
  959. await pool.query(`
  960. INSERT INTO users
  961. (id, username, password, role)
  962. VALUES (?, ?, '', 'user')
  963. `, [msg.from.id, username]);
  964. console.log(formatLog({
  965. 操作: '新增用户',
  966. ID: msg.from.id,
  967. 用户名: username,
  968. 角色: 'user',
  969. 时间: new Date().toLocaleString()
  970. }));
  971. }
  972. if (!existingGroup) {
  973. await handleBotAdded(msg, chatId, chatType, chatIdStr, null);
  974. } else if (existingGroup.group_type !== newType) {
  975. await handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup);
  976. }
  977. }
  978. if (existingGroup) {
  979. // 传递 newType 到 handleGroupUpdate 函数
  980. await handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus, newType);
  981. } else if (newStatus === 'member') {
  982. // 如果是新群组且机器人被添加为成员
  983. await handleBotAdded(msg, chatId, chatType, chatIdStr, null);
  984. }
  985. } catch (error) {
  986. console.error(formatLog({
  987. 错误: '处理群组状态变更失败',
  988. 详情: error.message
  989. }));
  990. }
  991. });
  992. // 处理机器人被移出群组
  993. bot.on('left_chat_member', async (msg) => {
  994. if (msg.left_chat_member.id === (await bot.getMe()).id) {
  995. const chatId = msg.chat.id.toString();
  996. try {
  997. // 更新数据库中的群组状态
  998. await pool.query(`
  999. UPDATE groups
  1000. SET is_active = false,
  1001. last_leave_time = CURRENT_TIMESTAMP
  1002. WHERE group_id = ?
  1003. `, [chatId]);
  1004. // 从内存中的允许列表中移除
  1005. const index = data.allowedGroups.indexOf(chatId);
  1006. if (index > -1) {
  1007. data.allowedGroups.splice(index, 1);
  1008. saveData();
  1009. }
  1010. // console.log(formatLog({
  1011. // ID: chatId,
  1012. // 名称: msg.chat.title || '未命名群组',
  1013. // 类型: msg.chat.type,
  1014. // 状态: '已移除',
  1015. // 移除时间: new Date().toLocaleString(),
  1016. // 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  1017. // }));
  1018. } catch (error) {
  1019. console.error(formatLog('处理机器人被移出群组失败', error));
  1020. }
  1021. }
  1022. });
  1023. // 保存数据
  1024. function saveData() {
  1025. try {
  1026. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  1027. } catch (error) {
  1028. console.error(formatLog('Error saving data', error));
  1029. }
  1030. }
  1031. // 加载数据
  1032. function loadData() {
  1033. try {
  1034. if (fs.existsSync(process.env.DB_FILE)) {
  1035. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  1036. data = {
  1037. ...data,
  1038. ...savedData
  1039. };
  1040. }
  1041. } catch (error) {
  1042. console.error(formatLog('Error loading data', error));
  1043. }
  1044. }
  1045. // 测试数据库连接并初始化
  1046. testConnection().then(() => {
  1047. return initDatabase();
  1048. }).then(() => {
  1049. // 加载数据
  1050. loadData();
  1051. // 启动服务器
  1052. const PORT = process.env.PORT || 3000;
  1053. app.listen(PORT, () => {
  1054. console.log(formatLog({
  1055. PORT: PORT
  1056. }));
  1057. console.log('机器人已准备就绪!');
  1058. });
  1059. }).catch(error => {
  1060. console.error(formatLog('启动失败', error));
  1061. process.exit(1);
  1062. });
  1063. // 导入公共路由
  1064. const publicRoutes = require('./routes/public');
  1065. // 注册公共路由
  1066. app.use('/api/public', publicRoutes);
  1067. // 错误处理中间件
  1068. app.use((err, req, res, next) => {
  1069. console.error(err.stack);
  1070. res.status(500).json({ message: '服务器错误' });
  1071. });
  1072. // 404 处理
  1073. app.use((req, res) => {
  1074. res.status(404).json({ message: '未找到请求的资源' });
  1075. });
  1076. module.exports = app;