index.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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('my_chat_member', async (msg) => {
  781. try {
  782. const chatId = msg.chat.id.toString();
  783. const chatTitle = msg.chat.title || '未命名群组';
  784. const creatorId = msg.from.id.toString();
  785. const newStatus = msg.new_chat_member.status;
  786. // 只处理机器人被添加到群组的情况
  787. if (newStatus === 'member' || newStatus === 'administrator') {
  788. // 检查群组是否已存在
  789. const [existingGroup] = await pool.query(
  790. 'SELECT * FROM groups WHERE group_id = ?',
  791. [chatId]
  792. );
  793. if (!existingGroup || existingGroup.length === 0) {
  794. // 创建新群组记录
  795. await pool.query(`
  796. INSERT INTO groups (
  797. group_id,
  798. group_name,
  799. creator_id,
  800. in_fee_rate,
  801. out_fee_rate,
  802. in_exchange_rate,
  803. out_exchange_rate,
  804. last_join_time,
  805. created_at,
  806. updated_at,
  807. operators
  808. ) VALUES (?, ?, ?, 0, 0, 1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '[]')
  809. `, [chatId, chatTitle, creatorId]);
  810. // 将群组添加到允许列表
  811. if (!data.allowedGroups.includes(chatId)) {
  812. data.allowedGroups.push(chatId);
  813. saveData();
  814. }
  815. // 发送欢迎消息
  816. await sendMessage(msg.chat.id, `感谢您添加我进入群组!\n\n我已初始化群组账单系统,您可以使用以下命令开始使用:\n\n• <code>/help</code> 查看使用指南\n• <code>/bill</code> 查看当前账单`);
  817. console.log(`新群组初始化成功 - 群组: ${chatTitle}, ID: ${chatId}, 创建者: ${creatorId}, 时间: ${new Date().toLocaleString()}`);
  818. } else {
  819. // 更新群组信息
  820. await pool.query(`
  821. UPDATE groups
  822. SET group_name = ?,
  823. last_join_time = CURRENT_TIMESTAMP,
  824. updated_at = CURRENT_TIMESTAMP
  825. WHERE group_id = ?
  826. `, [chatTitle, chatId]);
  827. // 确保群组在允许列表中
  828. if (!data.allowedGroups.includes(chatId)) {
  829. data.allowedGroups.push(chatId);
  830. saveData();
  831. }
  832. await sendMessage(msg.chat.id, `我已重新加入群组!\n\n您可以使用 <code>/help</code> 查看使用指南`);
  833. console.log(`群组信息更新成功 - 群组: ${chatTitle}, ID: ${chatId}, 时间: ${new Date().toLocaleString()}`);
  834. }
  835. }
  836. } catch (error) {
  837. console.error('处理机器人成员状态更新失败:', error);
  838. await sendMessage(msg.chat.id, '初始化群组失败,请稍后重试');
  839. }
  840. });
  841. // 保存数据
  842. function saveData() {
  843. try {
  844. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  845. } catch (error) {
  846. console.error(formatLog('Error saving data', error));
  847. }
  848. }
  849. // 加载数据
  850. function loadData() {
  851. try {
  852. if (fs.existsSync(process.env.DB_FILE)) {
  853. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  854. data = {
  855. ...data,
  856. ...savedData
  857. };
  858. }
  859. } catch (error) {
  860. console.error(formatLog('Error loading data', error));
  861. }
  862. }
  863. // 测试数据库连接并初始化
  864. testConnection().then(() => {
  865. // return initDatabase();
  866. }).then(() => {
  867. // 加载数据
  868. loadData();
  869. // 启动服务器
  870. const PORT = process.env.PORT || 3000;
  871. app.listen(PORT, () => {
  872. console.log(formatLog({
  873. PORT: PORT
  874. }));
  875. console.log('机器人已准备就绪!');
  876. });
  877. }).catch(error => {
  878. console.error(formatLog('启动失败', error));
  879. process.exit(1);
  880. });
  881. // 导入公共路由
  882. const publicRoutes = require('./routes/public');
  883. // 注册公共路由
  884. app.use('/api/public', publicRoutes);
  885. // 错误处理中间件
  886. app.use((err, req, res, next) => {
  887. console.error(err.stack);
  888. res.status(500).json({ message: '服务器错误' });
  889. });
  890. // 404 处理
  891. app.use((req, res) => {
  892. res.status(404).json({ message: '未找到请求的资源' });
  893. });
  894. module.exports = app;