index.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. // console.log(groupInfo.operators)
  89. // console.log(operators);
  90. // console.log(userIdStr);
  91. const isOperator = operators.some(op => op.operator_id == userIdStr);
  92. // 只在权限检查失败时输出详细日志
  93. if (!isCreator && !isOperator) {
  94. console.log(`权限检查失败 - 用户ID: ${userIdStr}, 群组ID: ${chatId}, 创建者ID: ${groupInfo.creator_id}, 操作人数量: ${operators.length}`);
  95. }
  96. return isCreator || isOperator;
  97. } catch (error) {
  98. console.error('检查用户权限失败:', error);
  99. return false;
  100. }
  101. }
  102. // 处理消息发送
  103. async function sendMessage(chatId, text, options = {}) {
  104. try {
  105. // 如果包含内联键盘,验证URL
  106. if (options.reply_markup && options.reply_markup.inline_keyboard) {
  107. const keyboard = generateInlineKeyboard(chatId);
  108. if (!keyboard) {
  109. // 如果键盘无效,发送不带键盘的消息
  110. return await bot.sendMessage(chatId, text, {
  111. parse_mode: 'HTML'
  112. });
  113. }
  114. options.reply_markup = keyboard;
  115. }
  116. return await bot.sendMessage(chatId, text, {
  117. ...options,
  118. parse_mode: 'HTML'
  119. });
  120. } catch (error) {
  121. console.error('发送消息失败:', error);
  122. if (error.message.includes('bot was kicked from the group chat')) {
  123. const index = data.allowedGroups.indexOf(chatId.toString());
  124. if (index > -1) {
  125. data.allowedGroups.splice(index, 1);
  126. saveData();
  127. console.log(`群组 ${chatId} 已被移除出允许列表`);
  128. }
  129. }
  130. return null;
  131. }
  132. }
  133. // - 1.快捷命令
  134. bot.on('message', async (msg) => {
  135. if (!isGroupAllowed(msg.chat.id)) return;
  136. const text = msg.text?.trim();
  137. if (!text) return;
  138. console.error(msg);
  139. // 0. 检查用户权限
  140. const hasPermission = await checkUserPermission(msg.chat.id, msg.from.id);
  141. if (!hasPermission) {
  142. // 如果不是创建人或操作人,直接返回
  143. return;
  144. }
  145. // 1. 处理入款命令
  146. if (text.startsWith('+')) {
  147. let amount, exchangeRate, feeRate;
  148. const parts = text.substring(1).split('/');
  149. amount = parseFloat(parts[0]);
  150. // 如果指定了汇率,则使用指定的汇率
  151. if (parts.length > 1) {
  152. exchangeRate = parseFloat(parts[1]);
  153. }
  154. // 如果指定了费率,则使用指定的费率
  155. if (parts.length > 2) {
  156. feeRate = parseFloat(parts[2]);
  157. }
  158. if (!isNaN(amount)) {
  159. const transactionData = {
  160. groupId: msg.chat.id.toString(),
  161. groupName: msg.chat.title || '未命名群组',
  162. amount: amount,
  163. type: 'deposit',
  164. exchangeRate: exchangeRate,
  165. feeRate: feeRate,
  166. operatorId: msg.from.id
  167. };
  168. // console.log(transactionData);
  169. try {
  170. const result = await Transaction.deposit(transactionData);
  171. if (result.success) {
  172. const billMessage = await generateBillMessage(msg.chat.id);
  173. if (billMessage) {
  174. await sendMessage(msg.chat.id, billMessage, {
  175. reply_markup: generateInlineKeyboard(msg.chat.id)
  176. });
  177. console.log(`入款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  178. } else {
  179. await sendMessage(msg.chat.id, '入款成功,但获取账单信息失败');
  180. console.log(`入款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  181. }
  182. } else {
  183. await sendMessage(msg.chat.id, result.message || '入款失败');
  184. console.log(`入款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  185. }
  186. } catch (error) {
  187. console.error('快捷入款失败:', error);
  188. await sendMessage(msg.chat.id, '记录入款失败,请稍后重试');
  189. }
  190. }
  191. }
  192. // 1.1 处理入款修正命令
  193. else if (text.startsWith('-') && !text.includes('下发')) {
  194. let amount, exchangeRate, feeRate;
  195. const parts = text.substring(1).split('/');
  196. amount = parseFloat(parts[0]);
  197. // 如果指定了汇率,则使用指定的汇率
  198. if (parts.length > 1) {
  199. exchangeRate = parseFloat(parts[1]);
  200. }
  201. // 如果指定了费率,则使用指定的费率
  202. if (parts.length > 2) {
  203. feeRate = parseFloat(parts[2]);
  204. }
  205. if (!isNaN(amount)) {
  206. const transactionData = {
  207. groupId: msg.chat.id.toString(),
  208. groupName: msg.chat.title || '未命名群组',
  209. amount: -amount,
  210. type: 'deposit',
  211. exchangeRate: exchangeRate,
  212. feeRate: feeRate,
  213. operatorId: msg.from.id
  214. };
  215. try {
  216. const result = await Transaction.deposit(transactionData);
  217. if (result.success) {
  218. const billMessage = await generateBillMessage(msg.chat.id);
  219. if (billMessage) {
  220. await sendMessage(msg.chat.id, billMessage, {
  221. reply_markup: generateInlineKeyboard(msg.chat.id)
  222. });
  223. console.log(`入款修正成功 - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  224. } else {
  225. await sendMessage(msg.chat.id, '入款修正成功,但获取账单信息失败');
  226. console.log(`入款修正成功(无账单) - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  227. }
  228. } else {
  229. await sendMessage(msg.chat.id, result.message || '入款修正失败');
  230. console.log(`入款修正失败 - 群组: ${msg.chat.title}, 金额: -${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  231. }
  232. } catch (error) {
  233. console.error('快捷入款修正失败:', error);
  234. await sendMessage(msg.chat.id, '记录入款修正失败,请稍后重试');
  235. }
  236. }
  237. }
  238. // 2. 处理下发命令
  239. else if (text.startsWith('下发')) {
  240. let amount, exchangeRate, feeRate;
  241. const parts = text.replace(/[^0-9./-]/g, '').split('/');
  242. amount = parseFloat(parts[0]);
  243. // 如果指定了汇率,则使用指定的汇率
  244. if (parts.length > 1) {
  245. exchangeRate = parseFloat(parts[1]);
  246. }
  247. // 如果指定了费率,则使用指定的费率
  248. if (parts.length > 2) {
  249. feeRate = parseFloat(parts[2]);
  250. }
  251. if (!isNaN(amount)) {
  252. // 获取当前账单信息
  253. const [records] = await pool.query(`
  254. SELECT t.*,
  255. COALESCE(t.fee_rate, g.in_fee_rate) as fee_rate,
  256. COALESCE(t.exchange_rate, g.in_exchange_rate) as exchange_rate,
  257. t.totalDeposit as total_deposit,
  258. t.totalWithdrawal as total_withdrawal,
  259. t.depositFee as deposit_fee,
  260. t.withdrawalFee as withdrawal_fee,
  261. t.totalUDeposit as total_u_deposit,
  262. t.totalUWithdrawal as total_u_withdrawal
  263. FROM transactions t
  264. LEFT JOIN groups g ON t.group_id = g.group_id
  265. WHERE t.group_id = ?
  266. AND DATE(t.time) = CURDATE()
  267. ORDER BY t.time DESC
  268. LIMIT 1
  269. `, [msg.chat.id.toString()]);
  270. if (!records || records.length === 0) {
  271. await sendMessage(msg.chat.id, '暂无交易记录,无法计算下发金额');
  272. return;
  273. }
  274. const latestRecord = records[0];
  275. const totalUDeposit = parseFloat(latestRecord.total_u_deposit) || 0;
  276. const totalUWithdrawal = parseFloat(latestRecord.total_u_withdrawal) || 0;
  277. // 直接使用输入的金额,不再限制
  278. const actualAmount = amount;
  279. if (actualAmount <= 0) {
  280. await sendMessage(msg.chat.id, '下发金额必须大于0');
  281. return;
  282. }
  283. const transactionData = {
  284. groupId: msg.chat.id.toString(),
  285. groupName: msg.chat.title || '未命名群组',
  286. amount: actualAmount,
  287. type: 'distribute',
  288. exchangeRate: exchangeRate,
  289. feeRate: feeRate,
  290. operatorId: msg.from.id
  291. };
  292. try {
  293. const result = await Transaction.distribute(transactionData);
  294. if (result.success) {
  295. const billMessage = await generateBillMessage(msg.chat.id);
  296. if (billMessage) {
  297. await sendMessage(msg.chat.id, billMessage, {
  298. reply_markup: generateInlineKeyboard(msg.chat.id)
  299. });
  300. console.log(`下发成功 - 群组: ${msg.chat.title}, 金额: ${actualAmount}, 时间: ${new Date().toLocaleString()}`);
  301. } else {
  302. await sendMessage(msg.chat.id, '下发成功,但获取账单信息失败');
  303. console.log(`下发成功(无账单) - 群组: ${msg.chat.title}, 金额: ${actualAmount}, 时间: ${new Date().toLocaleString()}`);
  304. }
  305. } else {
  306. await sendMessage(msg.chat.id, result.message || '下发失败');
  307. console.log(`下发失败 - 群组: ${msg.chat.title}, 金额: ${actualAmount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  308. }
  309. } catch (error) {
  310. console.error('快捷下发失败:', error);
  311. await sendMessage(msg.chat.id, '记录下发失败,请稍后重试');
  312. }
  313. }
  314. }
  315. // 2.1 处理下发修正命令
  316. else if (text.startsWith('下发-')) {
  317. let amount, exchangeRate, feeRate;
  318. const parts = text.replace(/[^0-9./-]/g, '').split('/');
  319. amount = parseFloat(parts[0]);
  320. // 如果指定了汇率,则使用指定的汇率
  321. if (parts.length > 1) {
  322. exchangeRate = parseFloat(parts[1]);
  323. }
  324. // 如果指定了费率,则使用指定的费率
  325. if (parts.length > 2) {
  326. feeRate = parseFloat(parts[2]);
  327. }
  328. if (!isNaN(amount)) {
  329. // 获取当前账单信息
  330. const [records] = await pool.query(`
  331. SELECT t.*,
  332. COALESCE(t.fee_rate, g.in_fee_rate) as fee_rate,
  333. COALESCE(t.exchange_rate, g.in_exchange_rate) as exchange_rate,
  334. t.totalDeposit as total_deposit,
  335. t.totalWithdrawal as total_withdrawal,
  336. t.depositFee as deposit_fee,
  337. t.withdrawalFee as withdrawal_fee,
  338. t.totalUDeposit as total_u_deposit,
  339. t.totalUWithdrawal as total_u_withdrawal
  340. FROM transactions t
  341. LEFT JOIN groups g ON t.group_id = g.group_id
  342. WHERE t.group_id = ?
  343. AND DATE(t.time) = CURDATE()
  344. ORDER BY t.time DESC
  345. LIMIT 1
  346. `, [msg.chat.id.toString()]);
  347. if (!records || records.length === 0) {
  348. await sendMessage(msg.chat.id, '暂无交易记录,无法计算下发修正金额');
  349. return;
  350. }
  351. const latestRecord = records[0];
  352. const totalUDeposit = parseFloat(latestRecord.total_u_deposit) || 0;
  353. const totalUWithdrawal = parseFloat(latestRecord.total_u_withdrawal) || 0;
  354. const remainingAmount = totalUDeposit - totalUWithdrawal;
  355. // 计算实际修正金额
  356. const actualAmount = Math.min(amount, totalUWithdrawal);
  357. if (actualAmount <= 0) {
  358. await sendMessage(msg.chat.id, '没有可修正的下发金额');
  359. return;
  360. }
  361. const transactionData = {
  362. groupId: msg.chat.id.toString(),
  363. groupName: msg.chat.title || '未命名群组',
  364. amount: -actualAmount,
  365. type: 'distribute',
  366. exchangeRate: exchangeRate,
  367. feeRate: feeRate,
  368. operatorId: msg.from.id
  369. };
  370. try {
  371. const result = await Transaction.distribute(transactionData);
  372. if (result.success) {
  373. const billMessage = await generateBillMessage(msg.chat.id);
  374. if (billMessage) {
  375. await sendMessage(msg.chat.id, billMessage, {
  376. reply_markup: generateInlineKeyboard(msg.chat.id)
  377. });
  378. console.log(`下发修正成功 - 群组: ${msg.chat.title}, 金额: -${actualAmount}, 时间: ${new Date().toLocaleString()}`);
  379. } else {
  380. await sendMessage(msg.chat.id, '下发修正成功,但获取账单信息失败');
  381. console.log(`下发修正成功(无账单) - 群组: ${msg.chat.title}, 金额: -${actualAmount}, 时间: ${new Date().toLocaleString()}`);
  382. }
  383. } else {
  384. await sendMessage(msg.chat.id, result.message || '下发修正失败');
  385. console.log(`下发修正失败 - 群组: ${msg.chat.title}, 金额: -${actualAmount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  386. }
  387. } catch (error) {
  388. console.error('快捷下发修正失败:', error);
  389. await sendMessage(msg.chat.id, '记录下发修正失败,请稍后重试');
  390. }
  391. }
  392. }
  393. // 3. 处理设置费率命令
  394. else if (text.startsWith('设置费率')) {
  395. const feeRate = parseFloat(text.replace('设置费率', '').trim());
  396. if (!isNaN(feeRate) && feeRate >= 0 && feeRate <= 100) {
  397. try {
  398. // 更新群组的入款和出款费率
  399. await pool.query(`
  400. UPDATE groups
  401. SET in_fee_rate = ?,
  402. out_fee_rate = ?,
  403. updated_at = CURRENT_TIMESTAMP
  404. WHERE group_id = ?
  405. `, [feeRate, feeRate, msg.chat.id.toString()]);
  406. await sendMessage(msg.chat.id, `费率${feeRate}%已设置成功`);
  407. console.log(`费率设置成功 - 群组: ${msg.chat.title}, 费率: ${feeRate}%, 时间: ${new Date().toLocaleString()}`);
  408. } catch (error) {
  409. console.error('设置费率失败:', error);
  410. await sendMessage(msg.chat.id, '设置费率失败,请稍后重试');
  411. }
  412. } else {
  413. await sendMessage(msg.chat.id, '费率设置失败,请输入0-100之间的数字');
  414. }
  415. }
  416. // 3.1 处理设置入款费率命令
  417. else if (text.startsWith('设置入款费率')) {
  418. const feeRate = parseFloat(text.replace('设置入款费率', '').trim());
  419. if (!isNaN(feeRate) && feeRate >= 0 && feeRate <= 100) {
  420. try {
  421. // 只更新群组的入款费率
  422. await pool.query(`
  423. UPDATE groups
  424. SET in_fee_rate = ?,
  425. updated_at = CURRENT_TIMESTAMP
  426. WHERE group_id = ?
  427. `, [feeRate, msg.chat.id.toString()]);
  428. await sendMessage(msg.chat.id, `入款费率${feeRate}%已设置成功`);
  429. console.log(`入款费率设置成功 - 群组: ${msg.chat.title}, 费率: ${feeRate}%, 时间: ${new Date().toLocaleString()}`);
  430. } catch (error) {
  431. console.error('设置入款费率失败:', error);
  432. await sendMessage(msg.chat.id, '设置入款费率失败,请稍后重试');
  433. }
  434. } else {
  435. await sendMessage(msg.chat.id, '入款费率设置失败,请输入0-100之间的数字');
  436. }
  437. }
  438. // 3.2 处理设置出款费率命令
  439. else if (text.startsWith('设置出款费率')) {
  440. const feeRate = parseFloat(text.replace('设置出款费率', '').trim());
  441. if (!isNaN(feeRate) && feeRate >= 0 && feeRate <= 100) {
  442. try {
  443. // 只更新群组的出款费率
  444. await pool.query(`
  445. UPDATE groups
  446. SET out_fee_rate = ?,
  447. updated_at = CURRENT_TIMESTAMP
  448. WHERE group_id = ?
  449. `, [feeRate, msg.chat.id.toString()]);
  450. await sendMessage(msg.chat.id, `出款费率${feeRate}%已设置成功`);
  451. console.log(`出款费率设置成功 - 群组: ${msg.chat.title}, 费率: ${feeRate}%, 时间: ${new Date().toLocaleString()}`);
  452. } catch (error) {
  453. console.error('设置出款费率失败:', error);
  454. await sendMessage(msg.chat.id, '设置出款费率失败,请稍后重试');
  455. }
  456. } else {
  457. await sendMessage(msg.chat.id, '出款费率设置失败,请输入0-100之间的数字');
  458. }
  459. }
  460. // 4. 处理设置汇率命令
  461. else if (text.startsWith('设置汇率')) {
  462. const exchangeRate = parseFloat(text.replace('设置汇率', '').trim());
  463. if (!isNaN(exchangeRate) && exchangeRate > 0) {
  464. try {
  465. // 更新群组的入款和出款汇率
  466. await pool.query(`
  467. UPDATE groups
  468. SET in_exchange_rate = ?,
  469. out_exchange_rate = ?,
  470. updated_at = CURRENT_TIMESTAMP
  471. WHERE group_id = ?
  472. `, [exchangeRate, exchangeRate, msg.chat.id.toString()]);
  473. await sendMessage(msg.chat.id, `汇率${exchangeRate}已设置成功`);
  474. console.log(`汇率设置成功 - 群组: ${msg.chat.title}, 汇率: ${exchangeRate}, 时间: ${new Date().toLocaleString()}`);
  475. } catch (error) {
  476. console.error('设置汇率失败:', error);
  477. await sendMessage(msg.chat.id, '设置汇率失败,请稍后重试');
  478. }
  479. } else {
  480. await sendMessage(msg.chat.id, '汇率设置失败,请输入大于0的数字');
  481. }
  482. }
  483. // 4.1 处理设置入款汇率命令
  484. else if (text.startsWith('设置入款汇率')) {
  485. const exchangeRate = parseFloat(text.replace('设置入款汇率', '').trim());
  486. if (!isNaN(exchangeRate) && exchangeRate > 0) {
  487. try {
  488. // 只更新群组的入款汇率
  489. await pool.query(`
  490. UPDATE groups
  491. SET in_exchange_rate = ?,
  492. updated_at = CURRENT_TIMESTAMP
  493. WHERE group_id = ?
  494. `, [exchangeRate, msg.chat.id.toString()]);
  495. await sendMessage(msg.chat.id, `入款汇率${exchangeRate}已设置成功`);
  496. console.log(`入款汇率设置成功 - 群组: ${msg.chat.title}, 汇率: ${exchangeRate}, 时间: ${new Date().toLocaleString()}`);
  497. } catch (error) {
  498. console.error('设置入款汇率失败:', error);
  499. await sendMessage(msg.chat.id, '设置入款汇率失败,请稍后重试');
  500. }
  501. } else {
  502. await sendMessage(msg.chat.id, '入款汇率设置失败,请输入大于0的数字');
  503. }
  504. }
  505. // 4.2 处理设置出款汇率命令
  506. else if (text.startsWith('设置出款汇率')) {
  507. const exchangeRate = parseFloat(text.replace('设置出款汇率', '').trim());
  508. if (!isNaN(exchangeRate) && exchangeRate > 0) {
  509. try {
  510. // 只更新群组的出款汇率
  511. await pool.query(`
  512. UPDATE groups
  513. SET out_exchange_rate = ?,
  514. updated_at = CURRENT_TIMESTAMP
  515. WHERE group_id = ?
  516. `, [exchangeRate, msg.chat.id.toString()]);
  517. await sendMessage(msg.chat.id, `出款汇率${exchangeRate}已设置成功`);
  518. console.log(`出款汇率设置成功 - 群组: ${msg.chat.title}, 汇率: ${exchangeRate}, 时间: ${new Date().toLocaleString()}`);
  519. } catch (error) {
  520. console.error('设置出款汇率失败:', error);
  521. await sendMessage(msg.chat.id, '设置出款汇率失败,请稍后重试');
  522. }
  523. } else {
  524. await sendMessage(msg.chat.id, '出款汇率设置失败,请输入大于0的数字');
  525. }
  526. }
  527. // 5. 处理设置操作人命令
  528. else if (text.startsWith('设置操作人')) {
  529. try {
  530. const groupId = msg.chat.id.toString();
  531. // const mentionedUser = msg.entities?.find(e => e.type === 'mention');
  532. if (!msg.reply_to_message.from.id) {
  533. // 如果没有@用户,回复原消息并提示设置用户名
  534. await bot.sendMessage(msg.chat.id, '请通过回复要添加操作人的消息设置', {
  535. reply_to_message_id: msg.message_id
  536. });
  537. return;
  538. }
  539. // 获取被@的用户名
  540. const username = msg.reply_to_message.from.first_name;//text.slice(mentionedUser.offset + 1, mentionedUser.offset + mentionedUser.length);
  541. // 获取群组信息
  542. const [group] = await pool.query(
  543. 'SELECT creator_id, COALESCE(operators, "[]") as operators FROM groups WHERE group_id = ?',
  544. [groupId]
  545. );
  546. if (!group || !group[0]) {
  547. await sendMessage(msg.chat.id, '群组信息不存在');
  548. return;
  549. }
  550. const groupInfo = group[0];
  551. const userId = msg.from.id.toString();
  552. // 检查操作权限(群组创建者或现有操作人)
  553. const isCreator = groupInfo.creator_id === userId;
  554. let operators = [];
  555. try {
  556. if (groupInfo.operators) {
  557. operators = JSON.parse(groupInfo.operators);
  558. if (!Array.isArray(operators)) {
  559. operators = [];
  560. }
  561. }
  562. } catch (e) {
  563. console.error('解析操作人列表失败:', e);
  564. operators = [];
  565. }
  566. const isOperator = operators.some(op => op.operator_id === userId);
  567. if (!isCreator && !isOperator) {
  568. await sendMessage(msg.chat.id, '您没有权限设置操作人');
  569. return;
  570. }
  571. // 获取被@用户的ID
  572. const [user] = await pool.query(
  573. 'SELECT id FROM users WHERE username = ?',
  574. [username]
  575. );
  576. let newOperatorId=msg.reply_to_message.from.id;
  577. let newOperatorUid=msg.reply_to_message.from.username;
  578. if (!user || !user[0]) {
  579. // 如果用户不存在,创建新用户
  580. try {
  581. const [result] = await pool.query(
  582. 'INSERT INTO users (id,uid,username, password, role) VALUES (?,?,?, ?, ?)',
  583. [newOperatorId,newOperatorUid,username, '', 'user']
  584. );
  585. // newOperatorId = result.insertId.toString();
  586. console.log(`创建新用户成功 - 用户名: ${username}, ID: ${newOperatorId}`);
  587. } catch (error) {
  588. console.error('创建新用户失败:', error);
  589. await sendMessage(msg.chat.id, '创建用户失败,请稍后重试');
  590. return;
  591. }
  592. } else {
  593. // newOperatorId = user[0].id.toString();
  594. }
  595. // 检查是否已经是操作人
  596. if (operators.some(op => op.operator_id === newOperatorId)) {
  597. await sendMessage(msg.chat.id, '该用户已经是操作人');
  598. return;
  599. }
  600. // 添加新操作人
  601. operators.push({
  602. operator_id: newOperatorId,
  603. operator_username: username,
  604. operator_uid:newOperatorUid,
  605. added_by: userId,
  606. added_at: new Date().toISOString()
  607. });
  608. // 更新群组
  609. await pool.query(
  610. 'UPDATE groups SET operators = ? WHERE group_id = ?',
  611. [JSON.stringify(operators), groupId]
  612. );
  613. await sendMessage(msg.chat.id, `已成功设置 @${username} 为操作人`);
  614. console.log(`设置操作人成功 - 群组: ${msg.chat.title}, 新操作人: ${username}, 设置者: ${msg.from.username || msg.from.first_name}, 时间: ${new Date().toLocaleString()}`);
  615. } catch (error) {
  616. console.error('设置操作人失败:', error);
  617. if (error.code === 'ER_BAD_FIELD_ERROR') {
  618. await sendMessage(msg.chat.id, '系统正在升级,请稍后再试');
  619. } else {
  620. await sendMessage(msg.chat.id, '设置操作人失败,请稍后重试');
  621. }
  622. }
  623. }
  624. // 6. 处理TRX地址
  625. else if (/^T[A-Za-z0-9]{33}$/.test(text)) {
  626. try {
  627. const groupId = msg.chat.id.toString();
  628. // 检查地址是否已存在
  629. const [existingAddress] = await pool.query(
  630. 'SELECT * FROM trx_addresses WHERE address = ? AND group_id = ?',
  631. [text, groupId]
  632. );
  633. if (existingAddress && existingAddress.length > 0) {
  634. // 更新使用次数和最后出现时间
  635. await pool.query(`
  636. UPDATE trx_addresses
  637. SET usage_count = usage_count + 1,
  638. last_seen_time = CURRENT_TIMESTAMP
  639. WHERE address = ? AND group_id = ?
  640. `, [text, groupId]);
  641. const newCount = existingAddress[0].usage_count + 1;
  642. await sendMessage(msg.chat.id, `此地址累计发送第${newCount}次`);
  643. console.log(`TRX地址使用次数更新 - 群组: ${msg.chat.title}, 地址: ${text}, 次数: ${newCount}, 时间: ${new Date().toLocaleString()}`);
  644. } else {
  645. // 插入新地址记录
  646. await pool.query(`
  647. INSERT INTO trx_addresses (address, group_id)
  648. VALUES (?, ?)
  649. `, [text, groupId]);
  650. await sendMessage(msg.chat.id, '此地址累计发送第1次');
  651. console.log(`新TRX地址记录 - 群组: ${msg.chat.title}, 地址: ${text}, 时间: ${new Date().toLocaleString()}`);
  652. }
  653. } catch (error) {
  654. console.error('处理TRX地址失败:', error);
  655. await sendMessage(msg.chat.id, '处理地址失败,请稍后重试');
  656. }
  657. }
  658. });
  659. // - 2.查看账单
  660. // 生成账单消息
  661. async function generateBillMessage(chatId) {
  662. try {
  663. console.log(`开始生成账单消息 - 群组ID: ${chatId}`);
  664. // 获取群组的最后加入时间和费率信息
  665. const [groupInfo] = await pool.query(
  666. 'SELECT last_join_time, in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate FROM groups WHERE group_id = ?',
  667. [chatId.toString()]
  668. );
  669. if (!groupInfo || groupInfo.length === 0) {
  670. console.log(`群组信息不存在 - 群组ID: ${chatId}`);
  671. return '暂无交易记录';
  672. }
  673. console.log(`获取到群组信息:`, groupInfo[0]);
  674. const lastJoinTime = groupInfo[0].last_join_time;
  675. const inFeeRate = parseFloat(groupInfo[0].in_fee_rate) || 0;
  676. const inExchangeRate = parseFloat(groupInfo[0].in_exchange_rate) || 0;
  677. const outFeeRate = parseFloat(groupInfo[0].out_fee_rate) || 0;
  678. const outExchangeRate = parseFloat(groupInfo[0].out_exchange_rate) || 0;
  679. // 获取机器人加入后的交易记录
  680. const [records] = await pool.query(`
  681. SELECT t.*,
  682. COALESCE(t.fee_rate, g.in_fee_rate) as fee_rate,
  683. COALESCE(t.exchange_rate, g.in_exchange_rate) as exchange_rate,
  684. t.totalDeposit as total_deposit,
  685. t.totalWithdrawal as total_withdrawal,
  686. t.depositFee as deposit_fee,
  687. t.withdrawalFee as withdrawal_fee,
  688. t.totalUDeposit as total_u_deposit,
  689. t.totalUWithdrawal as total_u_withdrawal
  690. FROM transactions t
  691. LEFT JOIN groups g ON t.group_id = g.group_id
  692. WHERE t.group_id = ?
  693. AND DATE(t.time) = CURDATE()
  694. ORDER BY t.time DESC
  695. `, [chatId.toString()]);
  696. if (!records || records.length === 0) {
  697. console.log(`今日无交易记录 - 群组ID: ${chatId}`);
  698. return '暂无交易记录';
  699. }
  700. console.log(`获取到交易记录数量: ${records.length}`);
  701. // 将记录按类型分类:入款和下发
  702. const deposits = records.filter(r => r.type === 'deposit');
  703. const withdrawals = records.filter(r => r.type === 'withdrawal');
  704. // 获取最新一条记录的总金额数据
  705. const latestRecord = records[0];
  706. console.log(`最新交易记录:`, latestRecord);
  707. const totalDeposit = parseFloat(latestRecord.total_deposit) || 0;
  708. const totalWithdrawal = parseFloat(latestRecord.total_withdrawal) || 0;
  709. const depositFee = parseFloat(latestRecord.deposit_fee) || 0;
  710. const withdrawalFee = parseFloat(latestRecord.withdrawal_fee) || 0;
  711. const totalUDeposit = parseFloat(latestRecord.total_u_deposit) || 0;
  712. const totalUWithdrawal = parseFloat(latestRecord.total_u_withdrawal) || 0;
  713. console.log(`金额数据:`, {
  714. totalDeposit,
  715. totalWithdrawal,
  716. depositFee,
  717. withdrawalFee,
  718. totalUDeposit,
  719. totalUWithdrawal
  720. });
  721. // 获取当前日期
  722. const today = new Date();
  723. const version = 'v29';
  724. const dateStr = today.toISOString().split('T')[0].replace(/-/g, '-');
  725. let message = `当前版本:<b>${dateStr}:${version}</b>\n\n`;
  726. // 添加入款记录
  727. if (deposits.length > 0) {
  728. message += `<b>入款笔数</b>:<code>${deposits.length}</code>\n`;
  729. deposits.forEach(deposit => {
  730. message += `<code>${moment(deposit.time).format('HH:mm:ss')} ${parseFloat(deposit.amount).toFixed(2)}</code>\n`;
  731. });
  732. message += '\n';
  733. } else {
  734. message += `<b>入款笔数</b>:<code>0</code>\n\n`;
  735. }
  736. // // 添加出款记录
  737. // if (withdrawals.length > 0) {
  738. // message += `<b>出款笔数</b>:<code>${withdrawals.length}</code>\n`;
  739. // withdrawals.forEach(withdrawal => {
  740. // message += `<code>${moment(withdrawal.time).format('HH:mm:ss')} ${parseFloat(withdrawal.amount).toFixed(2)}</code>\n`;
  741. // });
  742. // message += '\n';
  743. // } else {
  744. // message += `<b>出款笔数</b>:<code>0</code>\n\n`;
  745. // }
  746. // 添加费率信息
  747. message += `<b>入款费率</b>:<code>${inFeeRate}%</code>\n`;
  748. message += `<b>入款汇率</b>:<code>${inExchangeRate}</code>\n`;
  749. message += `<b>入款总额</b>:<code>${totalDeposit.toFixed(2)}</code>\n`;
  750. message += `<b>入款合计</b>:<code>${totalDeposit.toFixed(2)}|${totalUDeposit.toFixed(2)}U</code>\n\n`;
  751. // message += `<b>出款费率</b>:<code>${outFeeRate}%</code>\n`;
  752. // message += `<b>出款汇率</b>:<code>${outExchangeRate}</code>\n`;
  753. // message += `<b>出款总额</b>:<code>${totalWithdrawal.toFixed(2)}</code>\n`;
  754. // message += `<b>出款合计</b>:<code>${(totalWithdrawal - withdrawalFee).toFixed(2)}|${totalUWithdrawal.toFixed(2)}U</code>\n\n`;
  755. // 添加余额信息
  756. const remainingAmount = totalUDeposit - totalUWithdrawal;
  757. message += `<b>应下发</b>:<code>${(remainingAmount < 0 ? 0 : remainingAmount).toFixed(2)}U</code>\n`;
  758. message += `<b>已下发</b>:<code>${totalUWithdrawal.toFixed(2)}U</code>\n`;
  759. message += `<b>未下发</b>:<code>${(remainingAmount < 0 ? 0 : remainingAmount).toFixed(2)}U</code>`;
  760. console.log(`账单消息生成成功 - 群组ID: ${chatId}`);
  761. return message;
  762. } catch (error) {
  763. console.error('生成账单消息失败:', error);
  764. console.error('错误详情:', {
  765. message: error.message,
  766. stack: error.stack,
  767. chatId: chatId
  768. });
  769. return '获取账单信息失败,请稍后重试';
  770. }
  771. }
  772. // 生成内联键盘
  773. function generateInlineKeyboard(chatId) {
  774. const keyboard = {
  775. inline_keyboard: [
  776. [{
  777. text: '点击跳转完整账单',
  778. callback_data: `bill_page_${chatId}`
  779. }],
  780. [{
  781. text: '24小时商务对接',
  782. callback_data: 'business_contact'
  783. }]
  784. ]
  785. };
  786. return keyboard;
  787. }
  788. // 处理内联按钮回调
  789. bot.on('callback_query', async (callbackQuery) => {
  790. const chatId = callbackQuery.message.chat.id;
  791. const data = callbackQuery.data;
  792. try {
  793. if (data.startsWith('bill_page_')) {
  794. const groupId = data.split('_')[2];
  795. console.log('https://jfpay.top/admin/views/statistics_bill.html?groupId='+groupId)
  796. await bot.sendMessage(chatId, `点击查看完整账单:[完整账单](https://jfpay.top/admin/views/statistics_bill.html?groupId=${groupId})`, {parse_mode: 'Markdown'});
  797. } else if (data === 'business_contact') {
  798. await bot.sendMessage(chatId, `24小时商务对接:[点击跳转](https://t.me/yyyyaaaa123_bot)`, {parse_mode: 'Markdown'})
  799. }
  800. } catch (error) {
  801. console.log(error)
  802. console.error(formatLog('处理内联按钮回调失败', error));
  803. await bot.answerCallbackQuery(callbackQuery.id, {
  804. text: '操作失败,请稍后重试',
  805. show_alert: true
  806. });
  807. }
  808. });
  809. bot.onText(/\/bill/, async (msg) => {
  810. const billMessage = await generateBillMessage(msg.chat.id);
  811. sendMessage(msg.chat.id, billMessage, {
  812. reply_markup: generateInlineKeyboard(msg.chat.id)
  813. });
  814. });
  815. // - 3.帮助命令
  816. bot.onText(/\/help/, (msg) => {
  817. const helpMessage = `
  818. 🤖 <b>机器人使用指南</b>
  819. <b>📝 快捷命令</b>
  820. • <code>+数字</code> - 快速记录入款
  821. • <code>-数字</code> - 快速记录入款修正
  822. • <code>下发数字</code> - 快速记录下发
  823. • <code>下发-数字</code> - 快速记录下发修正
  824. <b>⚙️ 设置命令</b>
  825. • <code>设置费率数字</code> - 同时设置入款和出款费率
  826. • <code>设置入款费率数字</code> - 设置入款费率
  827. • <code>设置出款费率数字</code> - 设置出款费率
  828. • <code>设置汇率数字</code> - 同时设置入款和出款汇率
  829. • <code>设置入款汇率数字</code> - 设置入款汇率
  830. • <code>设置出款汇率数字</code> - 设置出款汇率
  831. • <code>回复消息"设置操作人"</code> - 将回复的用户设为群组操作人
  832. <b>📊 查询命令</b>
  833. • <code>/bill</code> - 查看当前账单
  834. • <code>/help</code> - 显示此帮助信息
  835. <b>💡 使用提示</b>
  836. • 所有金额输入请使用数字
  837. • 账单信息实时更新
  838. • 如需帮助请联系管理员
  839. `;
  840. sendMessage(msg.chat.id, helpMessage);
  841. });
  842. // - 4.群组信息更新
  843. // 处理机器人成员状态更新(包括被邀请到新群组)
  844. bot.on('my_chat_member', async (msg) => {
  845. try {
  846. const chatId = msg.chat.id.toString();
  847. const chatTitle = msg.chat.title || '未命名群组';
  848. const creatorId = msg.from.id.toString();
  849. const newStatus = msg.new_chat_member.status;
  850. // 只处理机器人被添加到群组的情况
  851. if (newStatus === 'member' || newStatus === 'administrator') {
  852. // 检查群组是否已存在
  853. const [existingGroup] = await pool.query(
  854. 'SELECT * FROM groups WHERE group_id = ?',
  855. [chatId]
  856. );
  857. if (!existingGroup || existingGroup.length === 0) {
  858. // 创建新群组记录
  859. await pool.query(`
  860. INSERT INTO groups (
  861. group_id,
  862. group_name,
  863. creator_id,
  864. in_fee_rate,
  865. out_fee_rate,
  866. in_exchange_rate,
  867. out_exchange_rate,
  868. last_join_time,
  869. created_at,
  870. updated_at,
  871. operators
  872. ) VALUES (?, ?, ?, 0, 0, 1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '[]')
  873. `, [chatId, chatTitle, creatorId]);
  874. // 将群组添加到允许列表
  875. if (!data.allowedGroups.includes(chatId)) {
  876. data.allowedGroups.push(chatId);
  877. saveData();
  878. }
  879. // 发送欢迎消息
  880. await sendMessage(msg.chat.id, `感谢您添加我进入群组!\n\n我已初始化群组账单系统,您可以使用以下命令开始使用:\n\n• <code>/help</code> 查看使用指南\n• <code>/bill</code> 查看当前账单`);
  881. console.log(`新群组初始化成功 - 群组: ${chatTitle}, ID: ${chatId}, 创建者: ${creatorId}, 时间: ${new Date().toLocaleString()}`);
  882. } else {
  883. // 更新群组信息
  884. await pool.query(`
  885. UPDATE groups
  886. SET group_name = ?,
  887. last_join_time = CURRENT_TIMESTAMP,
  888. updated_at = CURRENT_TIMESTAMP
  889. WHERE group_id = ?
  890. `, [chatTitle, chatId]);
  891. // 确保群组在允许列表中
  892. if (!data.allowedGroups.includes(chatId)) {
  893. data.allowedGroups.push(chatId);
  894. saveData();
  895. }
  896. await sendMessage(msg.chat.id, `我已重新加入群组!\n\n您可以使用 <code>/help</code> 查看使用指南`);
  897. console.log(`群组信息更新成功 - 群组: ${chatTitle}, ID: ${chatId}, 时间: ${new Date().toLocaleString()}`);
  898. }
  899. }
  900. } catch (error) {
  901. console.error('处理机器人成员状态更新失败:', error);
  902. await sendMessage(msg.chat.id, '初始化群组失败,请稍后重试');
  903. }
  904. });
  905. // 保存数据
  906. function saveData() {
  907. try {
  908. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  909. } catch (error) {
  910. console.error(formatLog('Error saving data', error));
  911. }
  912. }
  913. // 加载数据
  914. function loadData() {
  915. try {
  916. if (fs.existsSync(process.env.DB_FILE)) {
  917. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  918. data = {
  919. ...data,
  920. ...savedData
  921. };
  922. }
  923. } catch (error) {
  924. console.error(formatLog('Error loading data', error));
  925. }
  926. }
  927. // 测试数据库连接并初始化
  928. testConnection().then(() => {
  929. // return initDatabase();
  930. }).then(() => {
  931. // 加载数据
  932. loadData();
  933. // 启动服务器
  934. const PORT = process.env.PORT || 3000;
  935. app.listen(PORT, () => {
  936. console.log(formatLog({
  937. PORT: PORT
  938. }));
  939. console.log('机器人已准备就绪!');
  940. });
  941. }).catch(error => {
  942. console.error(formatLog('启动失败', error));
  943. process.exit(1);
  944. });
  945. // 导入公共路由
  946. const publicRoutes = require('./routes/public');
  947. // 注册公共路由
  948. app.use('/api/public', publicRoutes);
  949. // 错误处理中间件
  950. app.use((err, req, res, next) => {
  951. console.error(err.stack);
  952. res.status(500).json({ message: '服务器错误' });
  953. });
  954. // 404 处理
  955. app.use((req, res) => {
  956. res.status(404).json({ message: '未找到请求的资源' });
  957. });
  958. module.exports = app;