index.js 45 KB

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