index.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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 id = ?',
  618. [msg.reply_to_message.from.id]
  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. LIMIT 15
  701. `, [chatId.toString()]);
  702. // 获取今天的最新一条交易的累计数据
  703. const [todayLatestRecord] = await pool.query(`
  704. SELECT t.*,
  705. COALESCE(t.fee_rate, g.in_fee_rate) as fee_rate,
  706. COALESCE(t.exchange_rate, g.in_exchange_rate) as exchange_rate,
  707. t.totalDeposit as total_deposit,
  708. t.totalWithdrawal as total_withdrawal,
  709. t.depositFee as deposit_fee,
  710. t.withdrawalFee as withdrawal_fee,
  711. t.totalUDeposit as total_u_deposit,
  712. t.totalUWithdrawal as total_u_withdrawal
  713. FROM transactions t
  714. LEFT JOIN groups g ON t.group_id = g.group_id
  715. WHERE t.group_id = ?
  716. AND DATE(t.time) = CURDATE()
  717. ORDER BY t.time DESC
  718. LIMIT 1
  719. `, [chatId.toString()]);
  720. // 获取当前日期
  721. const today = new Date();
  722. const version = 'v29';
  723. const dateStr = today.toISOString().split('T')[0].replace(/-/g, '-');
  724. let message = `当前版本:<b>${dateStr}:${version}</b>\n\n`;
  725. // 添加入款记录(只显示当天的)
  726. if (todayRecords && todayRecords.length > 0) {
  727. message += `<b>入款笔数</b>:<code>${todayRecords.length}</code>(最近记录)\n`;
  728. todayRecords.forEach(deposit => {
  729. const amount = parseFloat(deposit.amount);
  730. const exchangeRate = parseFloat(deposit.exchange_rate) || 1;
  731. const feeRate = parseFloat(deposit.fee_rate) || 0;
  732. // 计算实际金额(扣除费率)
  733. let actualAmount;
  734. if (amount > 0) {
  735. // 入款:实际金额 = 金额 * (1 - 费率)
  736. actualAmount = Math.abs(amount) * (1 - feeRate / 100);
  737. } else {
  738. // 入款修正:实际金额 = 金额 * (1 - 费率)
  739. actualAmount = Math.abs(amount) * (1 - feeRate / 100);
  740. }
  741. // 计算USDT金额
  742. const uAmount = (actualAmount / exchangeRate) * (amount < 0 ? -1 : 1);
  743. // 显示计算过程
  744. const feeAmount = Math.abs(amount) * (feeRate / 100);
  745. const feeDisplay = feeRate > 0 ? `-${feeAmount.toFixed(2)}(${feeRate}%)` : '';
  746. const exchangeDisplay = exchangeRate !== 1 ? `÷${exchangeRate}` : '';
  747. message += `<code>${moment(deposit.time).format('HH:mm:ss')} ${parseFloat(deposit.amount).toFixed(2)}${feeDisplay}${exchangeDisplay} = ${uAmount.toFixed(2)}U</code>\n`;
  748. });
  749. message += '\n';
  750. } else {
  751. message += `<b>入款笔数</b>:<code>0</code>\n\n`;
  752. }
  753. // 添加费率信息
  754. message += `<b>入款费率</b>:<code>${inFeeRate}%</code>\n`;
  755. message += `<b>入款汇率</b>:<code>${inExchangeRate}</code>\n`;
  756. // 只有在今天有交易记录时才显示总额信息
  757. if (todayLatestRecord && todayLatestRecord.length > 0) {
  758. const totalDeposit = parseFloat(todayLatestRecord[0].total_deposit) || 0;
  759. const totalUDeposit = parseFloat(todayLatestRecord[0].total_u_deposit) || 0;
  760. const totalUWithdrawal = parseFloat(todayLatestRecord[0].total_u_withdrawal) || 0;
  761. message += `<b>入款总额</b>:<code>${totalDeposit.toFixed(2)}</code>\n`;
  762. message += `<b>入款合计</b>:<code>${totalDeposit.toFixed(2)}|${totalUDeposit.toFixed(2)}U</code>\n\n`;
  763. // 添加余额信息
  764. const remainingAmount = totalUDeposit - totalUWithdrawal;
  765. message += `<b>应下发</b>:<code>${(remainingAmount < 0 ? 0 : remainingAmount).toFixed(2)}U</code>\n`;
  766. message += `<b>已下发</b>:<code>${totalUWithdrawal.toFixed(2)}U</code>\n`;
  767. message += `<b>未下发</b>:<code>${(remainingAmount < 0 ? 0 : remainingAmount).toFixed(2)}U</code>`;
  768. } else {
  769. message += `<b>入款总额</b>:<code>0.00</code>\n`;
  770. message += `<b>入款合计</b>:<code>0.00|0.00U</code>\n\n`;
  771. message += `<b>应下发</b>:<code>0.00U</code>\n`;
  772. message += `<b>已下发</b>:<code>0.00U</code>\n`;
  773. message += `<b>未下发</b>:<code>0.00U</code>`;
  774. }
  775. console.log(`账单消息生成成功 - 群组ID: ${chatId}`);
  776. return message;
  777. } catch (error) {
  778. console.error('生成账单消息失败:', error);
  779. console.error('错误详情:', {
  780. message: error.message,
  781. stack: error.stack,
  782. chatId: chatId
  783. });
  784. return '获取账单信息失败,请稍后重试';
  785. }
  786. }
  787. // 生成内联键盘
  788. function generateInlineKeyboard(chatId) {
  789. const keyboard = {
  790. inline_keyboard: [
  791. [{
  792. text: '点击跳转完整账单',
  793. callback_data: `bill_page_${chatId}`
  794. }],
  795. [{
  796. text: '24小时商务对接',
  797. callback_data: 'business_contact'
  798. }]
  799. ]
  800. };
  801. return keyboard;
  802. }
  803. // 处理内联按钮回调
  804. bot.on('callback_query', async (callbackQuery) => {
  805. const chatId = callbackQuery.message.chat.id;
  806. const data = callbackQuery.data;
  807. try {
  808. if (data.startsWith('bill_page_')) {
  809. const groupId = data.split('_')[2];
  810. console.log('https://jfpay.top/admin/views/statistics_bill.html?groupId='+groupId)
  811. await bot.sendMessage(chatId, `点击查看完整账单:[完整账单](https://jfpay.top/admin/views/statistics_bill.html?groupId=${groupId})`, {parse_mode: 'Markdown'});
  812. } else if (data === 'business_contact') {
  813. await bot.sendMessage(chatId, `24小时商务对接:[点击跳转](https://t.me/yyyyaaaa123_bot)`, {parse_mode: 'Markdown'})
  814. }
  815. } catch (error) {
  816. console.log(error)
  817. console.error(formatLog('处理内联按钮回调失败', error));
  818. await bot.answerCallbackQuery(callbackQuery.id, {
  819. text: '操作失败,请稍后重试',
  820. show_alert: true
  821. });
  822. }
  823. });
  824. bot.onText(/\/bill/, async (msg) => {
  825. const billMessage = await generateBillMessage(msg.chat.id);
  826. sendMessage(msg.chat.id, billMessage, {
  827. reply_markup: generateInlineKeyboard(msg.chat.id)
  828. });
  829. });
  830. // - 3.帮助命令
  831. bot.onText(/\/help/, (msg) => {
  832. const helpMessage = `
  833. 🤖 <b>机器人使用指南</b>
  834. <b>📝 快捷命令</b>
  835. • <code>+数字</code> - 快速记录入款
  836. • <code>-数字</code> - 快速记录入款修正
  837. • <code>下发数字</code> - 快速记录下发
  838. • <code>下发-数字</code> - 快速记录下发修正
  839. <b>⚙️ 设置命令</b>
  840. • <code>设置费率数字</code> - 同时设置入款和出款费率
  841. • <code>设置入款费率数字</code> - 设置入款费率
  842. • <code>设置出款费率数字</code> - 设置出款费率
  843. • <code>设置汇率数字</code> - 同时设置入款和出款汇率
  844. • <code>设置入款汇率数字</code> - 设置入款汇率
  845. • <code>设置出款汇率数字</code> - 设置出款汇率
  846. • <code>回复消息"设置操作人"</code> - 将回复的用户设为群组操作人
  847. <b>📊 查询命令</b>
  848. • <code>/bill</code> - 查看当前账单
  849. • <code>/help</code> - 显示此帮助信息
  850. <b>💡 使用提示</b>
  851. • 所有金额输入请使用数字
  852. • 账单信息实时更新
  853. • 如需帮助请联系管理员
  854. `;
  855. sendMessage(msg.chat.id, helpMessage);
  856. });
  857. // - 4.群组信息更新
  858. // 处理机器人成员状态更新(包括被邀请到新群组)
  859. bot.on('my_chat_member', async (msg) => {
  860. try {
  861. const chatId = msg.chat.id.toString();
  862. const chatTitle = msg.chat.title || '未命名群组';
  863. const creatorId = msg.from.id.toString();
  864. const newStatus = msg.new_chat_member.status;
  865. // 只处理机器人被添加到群组的情况
  866. if (newStatus === 'member' || newStatus === 'administrator') {
  867. // 检查群组是否已存在
  868. const [existingGroup] = await pool.query(
  869. 'SELECT * FROM groups WHERE group_id = ?',
  870. [chatId]
  871. );
  872. if (!existingGroup || existingGroup.length === 0) {
  873. // 创建新群组记录
  874. await pool.query(`
  875. INSERT INTO groups (
  876. group_id,
  877. group_name,
  878. creator_id,
  879. in_fee_rate,
  880. out_fee_rate,
  881. in_exchange_rate,
  882. out_exchange_rate,
  883. last_join_time,
  884. created_at,
  885. updated_at,
  886. operators
  887. ) VALUES (?, ?, ?, 0, 0, 1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '[]')
  888. `, [chatId, chatTitle, creatorId]);
  889. // 将群组添加到允许列表
  890. if (!data.allowedGroups.includes(chatId)) {
  891. data.allowedGroups.push(chatId);
  892. saveData();
  893. }
  894. // 发送欢迎消息
  895. await sendMessage(msg.chat.id, `感谢您添加我进入群组!\n\n我已初始化群组账单系统,您可以使用以下命令开始使用:\n\n• <code>/help</code> 查看使用指南\n• <code>/bill</code> 查看当前账单`);
  896. console.log(`新群组初始化成功 - 群组: ${chatTitle}, ID: ${chatId}, 创建者: ${creatorId}, 时间: ${new Date().toLocaleString()}`);
  897. } else {
  898. // 更新群组信息
  899. await pool.query(`
  900. UPDATE groups
  901. SET group_name = ?,
  902. last_join_time = CURRENT_TIMESTAMP,
  903. updated_at = CURRENT_TIMESTAMP
  904. WHERE group_id = ?
  905. `, [chatTitle, chatId]);
  906. // 确保群组在允许列表中
  907. if (!data.allowedGroups.includes(chatId)) {
  908. data.allowedGroups.push(chatId);
  909. saveData();
  910. }
  911. await sendMessage(msg.chat.id, `我已重新加入群组!\n\n您可以使用 <code>/help</code> 查看使用指南`);
  912. console.log(`群组信息更新成功 - 群组: ${chatTitle}, ID: ${chatId}, 时间: ${new Date().toLocaleString()}`);
  913. }
  914. }
  915. } catch (error) {
  916. console.error('处理机器人成员状态更新失败:', error);
  917. await sendMessage(msg.chat.id, '初始化群组失败,请稍后重试');
  918. }
  919. });
  920. // 保存数据
  921. function saveData() {
  922. try {
  923. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  924. } catch (error) {
  925. console.error(formatLog('Error saving data', error));
  926. }
  927. }
  928. // 加载数据
  929. function loadData() {
  930. try {
  931. if (fs.existsSync(process.env.DB_FILE)) {
  932. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  933. data = {
  934. ...data,
  935. ...savedData
  936. };
  937. }
  938. } catch (error) {
  939. console.error(formatLog('Error loading data', error));
  940. }
  941. }
  942. // 测试数据库连接并初始化
  943. testConnection().then(() => {
  944. // 设置柬埔寨时间00:00重置任务(东七区)
  945. schedule.scheduleJob({second:0, minute: 0,hour: 0, tz: 'Asia/Bangkok' }, async () => {
  946. try {
  947. // 重置所有群组的费率和汇率
  948. await pool.query(`
  949. UPDATE groups
  950. SET in_fee_rate = 0,
  951. out_fee_rate = 0,
  952. in_exchange_rate = 1,
  953. out_exchange_rate = 1,
  954. updated_at = CURRENT_TIMESTAMP
  955. `);
  956. console.log('每日重置完成 - 时间:', new Date().toLocaleString());
  957. } catch (error) {
  958. console.error('每日重置失败:', error);
  959. }
  960. });
  961. console.log('已设置每日重置任务 - 东七区时间 00:00');
  962. }).then(() => {
  963. // 加载数据
  964. loadData();
  965. // 启动服务器
  966. const PORT = process.env.PORT || 3000;
  967. app.listen(PORT, () => {
  968. console.log(formatLog({
  969. PORT: PORT
  970. }));
  971. console.log('机器人已准备就绪!');
  972. });
  973. }).catch(error => {
  974. console.error(formatLog('启动失败', error));
  975. process.exit(1);
  976. });
  977. // 导入公共路由
  978. const publicRoutes = require('./routes/public');
  979. // 注册公共路由
  980. app.use('/api/public', publicRoutes);
  981. // 错误处理中间件
  982. app.use((err, req, res, next) => {
  983. console.error(err.stack);
  984. res.status(500).json({ message: '服务器错误' });
  985. });
  986. // 404 处理
  987. app.use((req, res) => {
  988. res.status(404).json({ message: '未找到请求的资源' });
  989. });
  990. module.exports = app;