index.js 43 KB

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