index.js 45 KB

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