index.js 43 KB

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