index.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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. // 获取群组的最后加入时间和费率信息
  601. const [groupInfo] = await pool.query(
  602. 'SELECT last_join_time, in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate FROM groups WHERE group_id = ?',
  603. [chatId.toString()]
  604. );
  605. if (!groupInfo || groupInfo.length === 0) {
  606. return '暂无交易记录';
  607. }
  608. const lastJoinTime = groupInfo[0].last_join_time;
  609. const inFeeRate = parseFloat(groupInfo[0].in_fee_rate) || 0;
  610. const inExchangeRate = parseFloat(groupInfo[0].in_exchange_rate) || 0;
  611. const outFeeRate = parseFloat(groupInfo[0].out_fee_rate) || 0;
  612. const outExchangeRate = parseFloat(groupInfo[0].out_exchange_rate) || 0;
  613. // 获取机器人加入后的交易记录
  614. const [records] = await pool.query(`
  615. SELECT t.*,
  616. COALESCE(t.fee_rate, g.in_fee_rate) as fee_rate,
  617. COALESCE(t.exchange_rate, g.in_exchange_rate) as exchange_rate,
  618. t.total_deposit,
  619. t.total_withdrawal,
  620. t.deposit_fee,
  621. t.withdrawal_fee,
  622. t.total_u_deposit,
  623. t.total_u_withdrawal
  624. FROM transactions t
  625. LEFT JOIN groups g ON t.group_id = g.group_id
  626. WHERE t.group_id = ?
  627. AND DATE(t.time) = CURDATE()
  628. ORDER BY t.time DESC
  629. `, [chatId.toString()]);
  630. if (!records || records.length === 0) {
  631. return '暂无交易记录';
  632. }
  633. // 将记录按类型分类:入款和下发
  634. const deposits = records.filter(r => r.type === 'deposit');
  635. const withdrawals = records.filter(r => r.type === 'withdrawal');
  636. // 获取最新一条记录的总金额数据
  637. const latestRecord = records[0];
  638. const totalDeposit = parseFloat(latestRecord.total_deposit) || 0;
  639. const totalWithdrawal = parseFloat(latestRecord.total_withdrawal) || 0;
  640. const depositFee = parseFloat(latestRecord.deposit_fee) || 0;
  641. const withdrawalFee = parseFloat(latestRecord.withdrawal_fee) || 0;
  642. const totalUDeposit = parseFloat(latestRecord.total_u_deposit) || 0;
  643. const totalUWithdrawal = parseFloat(latestRecord.total_u_withdrawal) || 0;
  644. // 计算剩余金额:总入款 - 入款手续费 - 总下发 - 下发手续费
  645. const remaining = totalDeposit - depositFee - totalWithdrawal - withdrawalFee;
  646. // 将剩余金额转换为U币:剩余金额 ÷ 入款汇率,保留2位小数
  647. const remainingU = (remaining / inExchangeRate).toFixed(2);
  648. // 获取当前日期
  649. const today = new Date();
  650. const version = 'v29';
  651. const dateStr = today.toISOString().split('T')[0].replace(/-/g, '-');
  652. let message = `当前版本:<b>${dateStr}:${version}</b>\n\n`;
  653. // 添加入款记录
  654. if (deposits.length > 0) {
  655. message += `<b>入款笔数</b>:<code>${deposits.length}</code>\n`;
  656. deposits.forEach(deposit => {
  657. message += `<code>${moment(deposit.time).format('HH:mm:ss')} ${parseFloat(deposit.amount).toFixed(2)}</code>\n`;
  658. });
  659. message += '\n';
  660. } else {
  661. message += `<b>入款笔数</b>:<code>0</code>\n\n`;
  662. }
  663. // 添加出款记录
  664. if (withdrawals.length > 0) {
  665. message += `<b>出款笔数</b>:<code>${withdrawals.length}</code>\n`;
  666. withdrawals.forEach(withdrawal => {
  667. message += `<code>${moment(withdrawal.time).format('HH:mm:ss')} ${parseFloat(withdrawal.amount).toFixed(2)}</code>\n`;
  668. });
  669. message += '\n';
  670. } else {
  671. message += `<b>出款笔数</b>:<code>0</code>\n\n`;
  672. }
  673. // 添加费率信息
  674. message += `<b>入款费率</b>:<code>${inFeeRate}%</code>\n`;
  675. message += `<b>入款汇率</b>:<code>${inExchangeRate}</code>\n`;
  676. message += `<b>入款总额</b>:<code>${totalDeposit.toFixed(2)}</code>\n`;
  677. message += `<b>入款合计</b>:<code>${(totalDeposit - depositFee).toFixed(2)}|${totalUDeposit.toFixed(2)}U</code>\n\n`;
  678. message += `<b>出款费率</b>:<code>${outFeeRate}%</code>\n`;
  679. message += `<b>出款汇率</b>:<code>${outExchangeRate}</code>\n`;
  680. message += `<b>出款总额</b>:<code>${totalWithdrawal.toFixed(2)}</code>\n`;
  681. message += `<b>出款合计</b>:<code>${(totalWithdrawal - withdrawalFee).toFixed(2)}|${totalUWithdrawal.toFixed(2)}U</code>\n\n`;
  682. // 添加余额信息
  683. message += `<b>应下发</b>:<code>${remainingU}U</code>\n`;
  684. message += `<b>已下发</b>:<code>${totalUWithdrawal.toFixed(2)}U</code>\n`;
  685. message += `<b>未下发</b>:<code>${(remainingU - totalUWithdrawal).toFixed(2)}U</code>`;
  686. return message;
  687. } catch (error) {
  688. console.error(formatLog('生成账单消息失败', error));
  689. return '获取账单信息失败,请稍后重试';
  690. }
  691. }
  692. // 生成内联键盘
  693. function generateInlineKeyboard(chatId) {
  694. const keyboard = {
  695. inline_keyboard: [
  696. [{
  697. text: '点击跳转完整账单',
  698. callback_data: `bill_page_${chatId}`
  699. }],
  700. [{
  701. text: '24小时商务对接',
  702. callback_data: 'business_contact'
  703. }]
  704. ]
  705. };
  706. return keyboard;
  707. }
  708. // 处理内联按钮回调
  709. bot.on('callback_query', async (callbackQuery) => {
  710. const chatId = callbackQuery.message.chat.id;
  711. const data = callbackQuery.data;
  712. try {
  713. if (data.startsWith('bill_page_')) {
  714. const groupId = data.split('_')[2];
  715. console.log('https://jfpay.top/admin/views/statistics_bill.html?groupId='+groupId)
  716. await bot.sendMessage(chatId, `点击查看完整账单:[完整账单](https://jfpay.top/admin/views/statistics_bill.html?groupId=${groupId})`, {parse_mode: 'Markdown'});
  717. } else if (data === 'business_contact') {
  718. await bot.sendMessage(chatId, `24小时商务对接:[点击跳转](https://t.me/yyyyaaaa123_bot)`, {parse_mode: 'Markdown'})
  719. }
  720. } catch (error) {
  721. console.log(error)
  722. console.error(formatLog('处理内联按钮回调失败', error));
  723. await bot.answerCallbackQuery(callbackQuery.id, {
  724. text: '操作失败,请稍后重试',
  725. show_alert: true
  726. });
  727. }
  728. });
  729. bot.onText(/\/bill/, async (msg) => {
  730. const billMessage = await generateBillMessage(msg.chat.id);
  731. sendMessage(msg.chat.id, billMessage, {
  732. reply_markup: generateInlineKeyboard(msg.chat.id)
  733. });
  734. });
  735. // - 3.帮助命令
  736. bot.onText(/\/help/, (msg) => {
  737. const helpMessage = `
  738. 🤖 <b>机器人使用指南</b>
  739. <b>📝 快捷命令</b>
  740. • <code>+数字</code> 快速记录入款
  741. • <code>-数字</code> 快速记录入款修正
  742. • <code>下发数字</code> 快速记录下发
  743. • <code>下发-数字</code> 快速记录下发修正
  744. <b>⚙️ 设置命令</b>
  745. • <code>设置费率数字</code> 同时设置入款和出款费率
  746. • <code>设置入款费率数字</code> 设置入款费率
  747. • <code>设置出款费率数字</code> 设置出款费率
  748. • <code>设置汇率数字</code> 同时设置入款和出款汇率
  749. • <code>设置入款汇率数字</code> 设置入款汇率
  750. • <code>设置出款汇率数字</code> 设置出款汇率
  751. • <code>设置操作人@用户名</code> 设置群组操作人
  752. <b>📊 查询命令</b>
  753. • <code>/bill</code> 查看当前账单
  754. • <code>/help</code> 显示此帮助信息
  755. <b>💡 使用提示</b>
  756. • 所有金额输入请使用数字
  757. • 账单信息实时更新
  758. • 如需帮助请联系管理员
  759. `;
  760. sendMessage(msg.chat.id, helpMessage);
  761. });
  762. // - 4.群组信息更新
  763. // 机器人被添加到群组
  764. bot.on('new_chat_members', async (msg) => {
  765. // 获取机器人ID
  766. const botInfo = await bot.getMe();
  767. // console.log('机器人信息:', botInfo);
  768. // 检查是否机器人被添加
  769. const botMember = msg.new_chat_members.find(member => member.id === botInfo.id);
  770. if (!botMember) {
  771. console.log('机器人未被添加,忽略事件');
  772. return;
  773. }
  774. try {
  775. const chatId = msg.chat.id.toString();
  776. const chatTitle = msg.chat.title || '未命名群组';
  777. const creatorId = msg.from.id.toString();
  778. // 检查群组是否已存在
  779. const [existingGroup] = await pool.query(
  780. 'SELECT * FROM groups WHERE group_id = ?',
  781. [chatId]
  782. );
  783. if (!existingGroup || existingGroup.length === 0) {
  784. // 创建新群组记录
  785. await pool.query(`
  786. INSERT INTO groups (
  787. group_id,
  788. group_name,
  789. creator_id,
  790. in_fee_rate,
  791. out_fee_rate,
  792. in_exchange_rate,
  793. out_exchange_rate,
  794. last_join_time,
  795. created_at,
  796. updated_at,
  797. operators
  798. ) VALUES (?, ?, ?, 0, 0, 1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '[]')
  799. `, [chatId, chatTitle, creatorId]);
  800. // 将群组添加到允许列表
  801. if (!data.allowedGroups.includes(chatId)) {
  802. data.allowedGroups.push(chatId);
  803. saveData();
  804. }
  805. // 发送欢迎消息
  806. await sendMessage(msg.chat.id, `感谢您添加我进入群组!\n\n我已初始化群组账单系统,您可以使用以下命令开始使用:\n\n• <code>/help</code> 查看使用指南\n• <code>/bill</code> 查看当前账单`);
  807. console.log(`新群组初始化成功 - 群组: ${chatTitle}, ID: ${chatId}, 创建者: ${creatorId}, 时间: ${new Date().toLocaleString()}`);
  808. } else {
  809. // 更新群组信息
  810. await pool.query(`
  811. UPDATE groups
  812. SET group_name = ?,
  813. last_join_time = CURRENT_TIMESTAMP,
  814. updated_at = CURRENT_TIMESTAMP
  815. WHERE group_id = ?
  816. `, [chatTitle, chatId]);
  817. // 确保群组在允许列表中
  818. if (!data.allowedGroups.includes(chatId)) {
  819. data.allowedGroups.push(chatId);
  820. saveData();
  821. }
  822. await sendMessage(msg.chat.id, `我已重新加入群组!\n\n您可以使用 <code>/help</code> 查看使用指南`);
  823. console.log(`群组信息更新成功 - 群组: ${chatTitle}, ID: ${chatId}, 时间: ${new Date().toLocaleString()}`);
  824. }
  825. } catch (error) {
  826. console.error('处理新群组失败:', error);
  827. await sendMessage(msg.chat.id, '初始化群组失败,请稍后重试');
  828. }
  829. });
  830. // 保存数据
  831. function saveData() {
  832. try {
  833. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  834. } catch (error) {
  835. console.error(formatLog('Error saving data', error));
  836. }
  837. }
  838. // 加载数据
  839. function loadData() {
  840. try {
  841. if (fs.existsSync(process.env.DB_FILE)) {
  842. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  843. data = {
  844. ...data,
  845. ...savedData
  846. };
  847. }
  848. } catch (error) {
  849. console.error(formatLog('Error loading data', error));
  850. }
  851. }
  852. // 测试数据库连接并初始化
  853. testConnection().then(() => {
  854. // return initDatabase();
  855. }).then(() => {
  856. // 加载数据
  857. loadData();
  858. // 启动服务器
  859. const PORT = process.env.PORT || 3000;
  860. app.listen(PORT, () => {
  861. console.log(formatLog({
  862. PORT: PORT
  863. }));
  864. console.log('机器人已准备就绪!');
  865. });
  866. }).catch(error => {
  867. console.error(formatLog('启动失败', error));
  868. process.exit(1);
  869. });
  870. // 导入公共路由
  871. const publicRoutes = require('./routes/public');
  872. // 注册公共路由
  873. app.use('/api/public', publicRoutes);
  874. // 错误处理中间件
  875. app.use((err, req, res, next) => {
  876. console.error(err.stack);
  877. res.status(500).json({ message: '服务器错误' });
  878. });
  879. // 404 处理
  880. app.use((req, res) => {
  881. res.status(404).json({ message: '未找到请求的资源' });
  882. });
  883. module.exports = app;