index.js 44 KB

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