index.js 44 KB

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