index.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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. function isAdmin(userId) {
  63. return process.env.ADMIN_IDS.split(',').includes(userId.toString());
  64. }
  65. // 处理消息发送
  66. async function sendMessage(chatId, text, options = {}) {
  67. try {
  68. // 如果包含内联键盘,验证URL
  69. if (options.reply_markup && options.reply_markup.inline_keyboard) {
  70. const keyboard = generateInlineKeyboard(chatId);
  71. if (!keyboard) {
  72. // 如果键盘无效,发送不带键盘的消息
  73. return await bot.sendMessage(chatId, text, {
  74. parse_mode: 'HTML'
  75. });
  76. }
  77. options.reply_markup = keyboard;
  78. }
  79. return await bot.sendMessage(chatId, text, {
  80. ...options,
  81. parse_mode: 'HTML'
  82. });
  83. } catch (error) {
  84. console.error('发送消息失败:', error);
  85. if (error.message.includes('bot was kicked from the group chat')) {
  86. const index = data.allowedGroups.indexOf(chatId.toString());
  87. if (index > -1) {
  88. data.allowedGroups.splice(index, 1);
  89. saveData();
  90. console.log(`群组 ${chatId} 已被移除出允许列表`);
  91. }
  92. }
  93. return null;
  94. }
  95. }
  96. // 处理快捷命令
  97. bot.on('message', async (msg) => {
  98. if (!isGroupAllowed(msg.chat.id)) return;
  99. const text = msg.text?.trim();
  100. if (!text) return;
  101. // 处理入款命令
  102. if (text.startsWith('+')) {
  103. let amount, exchangeRate, feeRate;
  104. const parts = text.substring(1).split('/');
  105. amount = parseFloat(parts[0]);
  106. // 如果指定了汇率,则使用指定的汇率
  107. if (parts.length > 1) {
  108. exchangeRate = parseFloat(parts[1]);
  109. }
  110. // 如果指定了费率,则使用指定的费率
  111. if (parts.length > 2) {
  112. feeRate = parseFloat(parts[2]);
  113. }
  114. if (!isNaN(amount)) {
  115. const transactionData = {
  116. groupId: msg.chat.id.toString(),
  117. groupName: msg.chat.title || '未命名群组',
  118. amount: amount,
  119. type: 'deposit',
  120. exchangeRate: exchangeRate, // 添加汇率字段
  121. feeRate: feeRate // 添加费率字段
  122. };
  123. try {
  124. const result = await Transaction.deposit(transactionData);
  125. if (result.success) {
  126. const billMessage = await generateBillMessage(msg.chat.id);
  127. if (billMessage) {
  128. await sendMessage(msg.chat.id, billMessage, {
  129. reply_markup: generateInlineKeyboard(msg.chat.id)
  130. });
  131. console.log(`入款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  132. } else {
  133. await sendMessage(msg.chat.id, '入款成功,但获取账单信息失败');
  134. console.log(`入款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  135. }
  136. } else {
  137. await sendMessage(msg.chat.id, result.message || '入款失败');
  138. console.log(`入款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  139. }
  140. } catch (error) {
  141. console.error('快捷入款失败:', error);
  142. await sendMessage(msg.chat.id, '记录入款失败,请稍后重试');
  143. }
  144. }
  145. }
  146. // 处理入款修正命令
  147. else if (text.startsWith('-') && !text.includes('下发')) {
  148. let amount, exchangeRate, feeRate;
  149. const parts = text.substring(1).split('/');
  150. amount = parseFloat(parts[0]);
  151. // 如果指定了汇率,则使用指定的汇率
  152. if (parts.length > 1) {
  153. exchangeRate = parseFloat(parts[1]);
  154. }
  155. // 如果指定了费率,则使用指定的费率
  156. if (parts.length > 2) {
  157. feeRate = parseFloat(parts[2]);
  158. }
  159. if (!isNaN(amount)) {
  160. const transactionData = {
  161. groupId: msg.chat.id.toString(),
  162. groupName: msg.chat.title || '未命名群组',
  163. amount: -amount,
  164. type: 'deposit',
  165. exchangeRate: exchangeRate, // 添加汇率字段
  166. feeRate: feeRate // 添加费率字段
  167. };
  168. try {
  169. const result = await Transaction.deposit(transactionData);
  170. if (result.success) {
  171. const billMessage = await generateBillMessage(msg.chat.id);
  172. if (billMessage) {
  173. await sendMessage(msg.chat.id, billMessage, {
  174. reply_markup: generateInlineKeyboard(msg.chat.id)
  175. });
  176. console.log(`入款修正成功 - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  177. } else {
  178. await sendMessage(msg.chat.id, '入款修正成功,但获取账单信息失败');
  179. console.log(`入款修正成功(无账单) - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  180. }
  181. } else {
  182. await sendMessage(msg.chat.id, result.message || '入款修正失败');
  183. console.log(`入款修正失败 - 群组: ${msg.chat.title}, 金额: -${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  184. }
  185. } catch (error) {
  186. console.error('快捷入款修正失败:', error);
  187. await sendMessage(msg.chat.id, '记录入款修正失败,请稍后重试');
  188. }
  189. }
  190. }
  191. // 处理回款命令
  192. else if (text.startsWith('下发')) {
  193. let amount, exchangeRate, feeRate;
  194. const parts = text.replace(/[^0-9./-]/g, '').split('/');
  195. amount = parseFloat(parts[0]);
  196. // 如果指定了汇率,则使用指定的汇率
  197. if (parts.length > 1) {
  198. exchangeRate = parseFloat(parts[1]);
  199. }
  200. // 如果指定了费率,则使用指定的费率
  201. if (parts.length > 2) {
  202. feeRate = parseFloat(parts[2]);
  203. }
  204. if (!isNaN(amount)) {
  205. const transactionData = {
  206. groupId: msg.chat.id.toString(),
  207. groupName: msg.chat.title || '未命名群组',
  208. amount: amount,
  209. type: 'withdrawal',
  210. exchangeRate: exchangeRate, // 添加汇率字段
  211. feeRate: feeRate // 添加费率字段
  212. };
  213. try {
  214. const result = await Transaction.withdrawal(transactionData);
  215. if (result.success) {
  216. const billMessage = await generateBillMessage(msg.chat.id);
  217. if (billMessage) {
  218. await sendMessage(msg.chat.id, billMessage, {
  219. reply_markup: generateInlineKeyboard(msg.chat.id)
  220. });
  221. console.log(`回款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  222. } else {
  223. await sendMessage(msg.chat.id, '回款成功,但获取账单信息失败');
  224. console.log(`回款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  225. }
  226. } else {
  227. await sendMessage(msg.chat.id, result.message || '回款失败');
  228. console.log(`回款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  229. }
  230. } catch (error) {
  231. console.error('快捷回款失败:', error);
  232. await sendMessage(msg.chat.id, '记录回款失败,请稍后重试');
  233. }
  234. }
  235. }
  236. // 处理回款修正命令
  237. else if (text.startsWith('下发-')) {
  238. let amount, exchangeRate, feeRate;
  239. const parts = text.replace(/[^0-9./-]/g, '').split('/');
  240. amount = parseFloat(parts[0]);
  241. // 如果指定了汇率,则使用指定的汇率
  242. if (parts.length > 1) {
  243. exchangeRate = parseFloat(parts[1]);
  244. }
  245. // 如果指定了费率,则使用指定的费率
  246. if (parts.length > 2) {
  247. feeRate = parseFloat(parts[2]);
  248. }
  249. if (!isNaN(amount)) {
  250. const transactionData = {
  251. groupId: msg.chat.id.toString(),
  252. groupName: msg.chat.title || '未命名群组',
  253. amount: -amount,
  254. type: 'withdrawal',
  255. exchangeRate: exchangeRate, // 添加汇率字段
  256. feeRate: feeRate // 添加费率字段
  257. };
  258. try {
  259. const result = await Transaction.withdrawal(transactionData);
  260. if (result.success) {
  261. const billMessage = await generateBillMessage(msg.chat.id);
  262. if (billMessage) {
  263. await sendMessage(msg.chat.id, billMessage, {
  264. reply_markup: generateInlineKeyboard(msg.chat.id)
  265. });
  266. console.log(`回款修正成功 - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  267. } else {
  268. await sendMessage(msg.chat.id, '回款修正成功,但获取账单信息失败');
  269. console.log(`回款修正成功(无账单) - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  270. }
  271. } else {
  272. await sendMessage(msg.chat.id, result.message || '回款修正失败');
  273. console.log(`回款修正失败 - 群组: ${msg.chat.title}, 金额: -${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  274. }
  275. } catch (error) {
  276. console.error('快捷回款修正失败:', error);
  277. await sendMessage(msg.chat.id, '记录回款修正失败,请稍后重试');
  278. }
  279. }
  280. }
  281. });
  282. // 处理新成员加入
  283. bot.on('new_chat_members', async (msg) => {
  284. const chatId = msg.chat.id;
  285. const newMembers = msg.new_chat_members;
  286. for (const member of newMembers) {
  287. if (member.id === (await bot.getMe()).id) {
  288. // 检查群组是否在允许列表中
  289. const chatIdStr = chatId.toString();
  290. try {
  291. // 先检查数据库中是否存在该群组
  292. const existingGroup = await Group.findByGroupId(chatIdStr);
  293. if (existingGroup) {
  294. // 如果群组存在,更新群组状态为活跃,同时更新群组名称和加入时间
  295. await pool.query(`
  296. UPDATE groups
  297. SET is_active = true,
  298. group_name = ?,
  299. last_join_time = CURRENT_TIMESTAMP
  300. WHERE group_id = ?
  301. `, [msg.chat.title || existingGroup.group_name, chatIdStr]);
  302. // 更新内存中的群组列表
  303. if (!data.allowedGroups.includes(chatIdStr)) {
  304. data.allowedGroups.push(chatIdStr);
  305. saveData();
  306. }
  307. // console.log(formatLog({
  308. // ID: chatIdStr,
  309. // 名称: msg.chat.title || existingGroup.group_name,
  310. // 类型: msg.chat.type,
  311. // 状态: '重新激活',
  312. // 更新时间: new Date().toLocaleString()
  313. // }));
  314. // 发送欢迎消息并显示当前账单
  315. await sendMessage(chatId, '感谢重新添加我为群组成员!');
  316. const billMessage = await generateBillMessage(chatId);
  317. if (billMessage) {
  318. await sendMessage(chatId, billMessage, {
  319. reply_markup: generateInlineKeyboard(chatId)
  320. });
  321. }
  322. } else {
  323. // 如果是新群组,打印被添加到新群组的信息
  324. console.log(formatLog({
  325. ID: chatId,
  326. 名称: msg.chat.title || '未命名群组',
  327. 类型: msg.chat.type,
  328. 描述: msg.chat.description || '无',
  329. '添加者信息': {
  330. ID: msg.from.id,
  331. 用户名: msg.from.username || '无',
  332. 姓名: msg.from.first_name,
  333. ...(msg.from.last_name && {
  334. 姓: msg.from.last_name
  335. })
  336. },
  337. 添加时间: new Date().toLocaleString()
  338. }));
  339. // 如果群组不存在,创建新群组
  340. const groupData = {
  341. groupId: chatIdStr,
  342. groupName: msg.chat.title || '未命名群组',
  343. groupType: msg.chat.type === 'private' ? 'personal' : msg.chat.type,
  344. creatorId: msg.from.id.toString()
  345. };
  346. console.log(formatLog(groupData));
  347. try {
  348. // 直接使用 SQL 插入群组数据
  349. const [result] = await pool.query(`
  350. INSERT INTO groups
  351. (group_id, group_name, group_type, creator_id, is_active, last_join_time)
  352. VALUES (?, ?, ?, ?, true, CURRENT_TIMESTAMP)
  353. `, [
  354. groupData.groupId,
  355. groupData.groupName,
  356. groupData.groupType,
  357. groupData.creatorId
  358. ]);
  359. console.log(formatLog(result));
  360. // 更新内存中的群组列表
  361. if (!data.allowedGroups.includes(chatIdStr)) {
  362. data.allowedGroups.push(chatIdStr);
  363. saveData();
  364. console.log(formatLog({
  365. ID: chatIdStr,
  366. 名称: groupData.groupName,
  367. 类型: groupData.groupType,
  368. 状态: '已启用',
  369. 添加时间: new Date().toLocaleString(),
  370. 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  371. }));
  372. }
  373. console.log(formatLog({
  374. ID: chatIdStr,
  375. 名称: groupData.groupName,
  376. 类型: groupData.groupType,
  377. 状态: '已启用',
  378. 添加时间: new Date().toLocaleString(),
  379. 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  380. }));
  381. try {
  382. // 尝试发送欢迎消息
  383. const welcomeMessage = await bot.sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。', {
  384. parse_mode: 'HTML'
  385. });
  386. console.log(formatLog(welcomeMessage));
  387. // 尝试发送账单消息
  388. const billMessage = await generateBillMessage(chatId);
  389. if (billMessage) {
  390. const billResult = await bot.sendMessage(chatId, billMessage, {
  391. parse_mode: 'HTML',
  392. reply_markup: generateInlineKeyboard(chatId)
  393. });
  394. console.log(formatLog(billResult));
  395. }
  396. } catch (messageError) {
  397. console.error(formatLog(messageError));
  398. }
  399. } catch (error) {
  400. console.error(formatLog('创建群组过程中出错', error));
  401. try {
  402. await bot.sendMessage(chatId, '添加群组失败,请联系管理员。', {
  403. parse_mode: 'HTML'
  404. });
  405. } catch (messageError) {
  406. console.error(formatLog('发送错误消息失败', messageError));
  407. }
  408. }
  409. }
  410. } catch (error) {
  411. console.error(formatLog('处理群组加入失败', error));
  412. await sendMessage(chatId, '添加群组失败,请联系管理员。');
  413. }
  414. } else {
  415. // 其他新成员
  416. console.log(formatLog({
  417. member: member.username || member.first_name + ' (' + member.id + ')'
  418. }));
  419. await sendMessage(chatId, `欢迎 ${member.username || member.first_name} 加入群组!`);
  420. }
  421. }
  422. });
  423. // 处理机器人被移出群组
  424. bot.on('left_chat_member', async (msg) => {
  425. if (msg.left_chat_member.id === (await bot.getMe()).id) {
  426. const chatId = msg.chat.id.toString();
  427. try {
  428. // 更新数据库中的群组状态
  429. await pool.query(`
  430. UPDATE groups
  431. SET is_active = false,
  432. last_leave_time = CURRENT_TIMESTAMP
  433. WHERE group_id = ?
  434. `, [chatId]);
  435. // 从内存中的允许列表中移除
  436. const index = data.allowedGroups.indexOf(chatId);
  437. if (index > -1) {
  438. data.allowedGroups.splice(index, 1);
  439. saveData();
  440. }
  441. // console.log(formatLog({
  442. // ID: chatId,
  443. // 名称: msg.chat.title || '未命名群组',
  444. // 类型: msg.chat.type,
  445. // 状态: '已移除',
  446. // 移除时间: new Date().toLocaleString(),
  447. // 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  448. // }));
  449. } catch (error) {
  450. console.error(formatLog('处理机器人被移出群组失败', error));
  451. }
  452. }
  453. });
  454. // 处理管理员命令
  455. bot.onText(/\/addgroup (.+)/, async (msg, match) => {
  456. if (!isAdmin(msg.from.id)) {
  457. sendMessage(msg.chat.id, '您没有权限执行此命令。');
  458. return;
  459. }
  460. const groupId = match[1].trim();
  461. if (!data.allowedGroups.includes(groupId)) {
  462. try {
  463. // 使用 createGroup 创建新群组
  464. const groupData = {
  465. groupId: groupId,
  466. groupName: '手动添加的群组',
  467. groupType: 'public',
  468. creatorId: msg.from.id.toString()
  469. };
  470. const result = await createGroup({
  471. body: groupData
  472. });
  473. if (result) {
  474. data.allowedGroups.push(groupId);
  475. saveData();
  476. console.log(formatLog({
  477. ID: groupId,
  478. 名称: groupData.groupName,
  479. 状态: '已启用',
  480. 添加时间: new Date().toLocaleString(),
  481. 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  482. }));
  483. sendMessage(msg.chat.id, `群组 ${groupId} 已添加到允许列表。`);
  484. } else {
  485. sendMessage(msg.chat.id, '添加群组失败,请检查群组ID是否正确。');
  486. }
  487. } catch (error) {
  488. console.error(formatLog('创建群组失败', error));
  489. sendMessage(msg.chat.id, '添加群组失败,请稍后重试。');
  490. }
  491. } else {
  492. sendMessage(msg.chat.id, '该群组已在允许列表中。');
  493. }
  494. });
  495. // 处理查看账单命令
  496. bot.onText(/\/bill/, async (msg) => {
  497. const billMessage = await generateBillMessage(msg.chat.id);
  498. sendMessage(msg.chat.id, billMessage, {
  499. reply_markup: generateInlineKeyboard(msg.chat.id)
  500. });
  501. });
  502. // 更新帮助命令
  503. bot.onText(/\/help/, (msg) => {
  504. const helpMessage = `
  505. 🤖 机器人使用指南
  506. 📝 基础命令
  507. • /deposit 数字 - 记录入款
  508. • /withdraw 数字 - 记录下发
  509. • /bill - 查看当前账单
  510. • /help - 显示此帮助信息
  511. ⚡️ 快捷命令
  512. • +数字 - 快速记录入款(例如:+2000)
  513. • -数字 - 快速记录下发(例如:-2000)
  514. 👨‍💼 管理员命令
  515. • /addgroup 群组ID - 添加允许的群组
  516. • /removegroup 群组ID - 移除允许的群组
  517. • /listgroups - 列出所有允许的群组
  518. 💡 使用提示
  519. • 所有金额输入请使用数字
  520. • 账单信息实时更新
  521. • 如需帮助请联系管理员
  522. `;
  523. sendMessage(msg.chat.id, helpMessage);
  524. });
  525. // 生成账单消息
  526. async function generateBillMessage(chatId) {
  527. try {
  528. // 获取群组的最后加入时间和费率信息
  529. const [groupInfo] = await pool.query(
  530. 'SELECT last_join_time, in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate FROM groups WHERE group_id = ?',
  531. [chatId.toString()]
  532. );
  533. if (!groupInfo || groupInfo.length === 0) {
  534. return '暂无交易记录';
  535. }
  536. const lastJoinTime = groupInfo[0].last_join_time;
  537. const inFeeRate = parseFloat(groupInfo[0].in_fee_rate) || 0;
  538. const inExchangeRate = parseFloat(groupInfo[0].in_exchange_rate) || 0;
  539. const outFeeRate = parseFloat(groupInfo[0].out_fee_rate) || 0;
  540. const outExchangeRate = parseFloat(groupInfo[0].out_exchange_rate) || 0;
  541. // 获取机器人加入后的交易记录
  542. const [records] = await pool.query(`
  543. SELECT t.*,
  544. COALESCE(t.fee_rate, g.in_fee_rate) as fee_rate,
  545. COALESCE(t.exchange_rate, g.in_exchange_rate) as exchange_rate
  546. FROM transactions t
  547. LEFT JOIN groups g ON t.group_id = g.group_id
  548. WHERE t.group_id = ?
  549. AND DATE(t.time) = CURDATE()
  550. ORDER BY t.time DESC
  551. `, [chatId.toString()]);
  552. if (!records || records.length === 0) {
  553. return '暂无交易记录';
  554. }
  555. const deposits = records.filter(r => r.type === 'deposit');
  556. const withdrawals = records.filter(r => r.type === 'withdrawal');
  557. const totalDeposit = deposits.reduce((sum, d) => sum + parseFloat(d.amount), 0);
  558. const totalWithdrawal = withdrawals.reduce((sum, w) => sum + parseFloat(w.amount), 0);
  559. const depositFee = totalDeposit * (inFeeRate / 100);
  560. const withdrawalFee = totalWithdrawal * (outFeeRate / 100);
  561. const remaining = totalDeposit - depositFee - totalWithdrawal - withdrawalFee;
  562. const remainingU = (remaining / inExchangeRate).toFixed(2);
  563. // 获取当前日期
  564. const today = new Date();
  565. const version = 'v29';
  566. const dateStr = today.toISOString().split('T')[0].replace(/-/g, '-');
  567. let message = `当前版本:<b>${dateStr}:${version}</b>\n\n`;
  568. // 添加入款记录
  569. if (deposits.length > 0) {
  570. message += `<b>入款笔数</b>:<code>${deposits.length}</code>\n`;
  571. deposits.forEach(deposit => {
  572. message += `<code>${moment(deposit.time).format('HH:mm:ss')} ${parseFloat(deposit.amount).toFixed(2)}</code>\n`;
  573. });
  574. message += '\n';
  575. } else {
  576. message += `<b>入款笔数</b>:<code>0</code>\n\n`;
  577. }
  578. // 添加出款记录
  579. if (withdrawals.length > 0) {
  580. message += `<b>出款笔数</b>:<code>${withdrawals.length}</code>\n`;
  581. withdrawals.forEach(withdrawal => {
  582. message += `<code>${moment(withdrawal.time).format('HH:mm:ss')} ${parseFloat(withdrawal.amount).toFixed(2)}</code>\n`;
  583. });
  584. message += '\n';
  585. } else {
  586. message += `<b>出款笔数</b>:<code>0</code>\n\n`;
  587. }
  588. // 添加费率信息
  589. message += `<b>入款费率</b>:<code>${inFeeRate}%</code>\n`;
  590. message += `<b>入款汇率</b>:<code>${inExchangeRate}</code>\n`;
  591. message += `<b>入款总额</b>:<code>${totalDeposit.toFixed(2)}</code>\n`;
  592. message += `<b>入款合计</b>:<code>${(totalDeposit - depositFee).toFixed(2)}|${((totalDeposit - depositFee) / inExchangeRate).toFixed(2)}U</code>\n\n`;
  593. message += `<b>出款费率</b>:<code>${outFeeRate}%</code>\n`;
  594. message += `<b>出款汇率</b>:<code>${outExchangeRate}</code>\n`;
  595. message += `<b>出款总额</b>:<code>${totalWithdrawal.toFixed(2)}</code>\n`;
  596. message += `<b>出款合计</b>:<code>${(totalWithdrawal - withdrawalFee).toFixed(2)}|${((totalWithdrawal - withdrawalFee) / outExchangeRate).toFixed(2)}U</code>\n\n`;
  597. // 添加余额信息
  598. message += `<b>应下发</b>:<code>${remainingU}U</code>\n`;
  599. message += `<b>已下发</b>:<code>${(totalWithdrawal / outExchangeRate).toFixed(2)}U</code>\n`;
  600. message += `<b>未下发</b>:<code>${(remainingU - (totalWithdrawal / outExchangeRate)).toFixed(2)}U</code>`;
  601. return message;
  602. } catch (error) {
  603. console.error(formatLog('生成账单消息失败', error));
  604. return '获取账单信息失败,请稍后重试';
  605. }
  606. }
  607. // 生成内联键盘
  608. function generateInlineKeyboard(chatId) {
  609. const keyboard = {
  610. inline_keyboard: [
  611. [{
  612. text: '点击跳转完整账单',
  613. callback_data: `bill_page_${chatId}`
  614. }],
  615. [{
  616. text: '24小时商务对接',
  617. callback_data: 'business_contact'
  618. }]
  619. ]
  620. };
  621. return keyboard;
  622. }
  623. // 处理内联按钮回调
  624. bot.on('callback_query', async (callbackQuery) => {
  625. const chatId = callbackQuery.message.chat.id;
  626. const data = callbackQuery.data;
  627. try {
  628. if (data.startsWith('bill_page_')) {
  629. const groupId = data.split('_')[2];
  630. await bot.answerCallbackQuery(callbackQuery.id, {
  631. url: 'https://google.com'
  632. });
  633. } else if (data === 'business_contact') {
  634. await bot.answerCallbackQuery(callbackQuery.id, {
  635. url: 'https://t.me/your_business_account'
  636. });
  637. }
  638. } catch (error) {
  639. console.error(formatLog('处理内联按钮回调失败', error));
  640. await bot.answerCallbackQuery(callbackQuery.id, {
  641. text: '操作失败,请稍后重试',
  642. show_alert: true
  643. });
  644. }
  645. });
  646. // 保存数据
  647. function saveData() {
  648. try {
  649. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  650. } catch (error) {
  651. console.error(formatLog('Error saving data', error));
  652. }
  653. }
  654. // 加载数据
  655. function loadData() {
  656. try {
  657. if (fs.existsSync(process.env.DB_FILE)) {
  658. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  659. data = {
  660. ...data,
  661. ...savedData
  662. };
  663. }
  664. } catch (error) {
  665. console.error(formatLog('Error loading data', error));
  666. }
  667. }
  668. // 测试数据库连接并初始化
  669. testConnection().then(() => {
  670. return initDatabase();
  671. }).then(() => {
  672. // 加载数据
  673. loadData();
  674. // 启动服务器
  675. const PORT = process.env.PORT || 3000;
  676. app.listen(PORT, () => {
  677. console.log(formatLog({
  678. PORT: PORT
  679. }));
  680. console.log('机器人已准备就绪!');
  681. });
  682. }).catch(error => {
  683. console.error(formatLog('启动失败', error));
  684. process.exit(1);
  685. });
  686. // 处理机器人被添加到群组
  687. async function handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup) {
  688. try {
  689. // 获取群组链接
  690. const chatInfo = await bot.getChat(chatId);
  691. const groupInfo = {
  692. ID: chatId,
  693. 名称: msg.chat.title || '未命名群组',
  694. 类型: chatType,
  695. 状态: existingGroup ? '重新激活' : '已激活',
  696. 群组链接: chatInfo.invite_link || '未设置',
  697. 更新时间: new Date().toLocaleString()
  698. };
  699. // console.log('机器人首次被添加到群组');
  700. // console.log(formatLog(groupInfo));
  701. // 如果群组不存在,创建新群组
  702. if (!existingGroup) {
  703. const groupData = {
  704. groupId: chatIdStr,
  705. groupName: msg.chat.title || '未命名群组',
  706. groupType: chatType === 'private' ? 'private' : 'public',
  707. creatorId: msg.from.id.toString()
  708. };
  709. const id = await Group.create({
  710. groupId: groupData.groupId,
  711. groupName: groupData.groupName,
  712. creatorId: groupData.creatorId
  713. });
  714. if (id) {
  715. // 更新内存中的群组列表
  716. if (!data.allowedGroups.includes(chatIdStr)) {
  717. data.allowedGroups.push(chatIdStr);
  718. saveData();
  719. }
  720. console.log('机器人首次被添加到群组');
  721. console.log(formatLog(groupInfo));
  722. await sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。');
  723. } else {
  724. await sendMessage(chatId, '添加群组失败,请联系管理员。');
  725. }
  726. }
  727. } catch (error) {
  728. console.error(formatLog({
  729. 错误: '处理机器人首次加入群组失败',
  730. 详情: error.message
  731. }));
  732. await sendMessage(chatId, '添加群组失败,请联系管理员。');
  733. }
  734. }
  735. // 处理群组信息更新
  736. async function handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus) {
  737. const connection = await pool.getConnection();
  738. await connection.beginTransaction();
  739. try {
  740. // 更新群组ID和类型
  741. const newType = chatType === 'private' ? 'private' :
  742. chatType === 'supergroup' ? 'supergroup' : 'group';
  743. const oldGroupId = existingGroup.group_id;
  744. // 如果群组ID发生变化,更新所有相关记录
  745. if (existingGroup.group_type != newType) {
  746. console.log(formatLog({
  747. 操作: '群组类型更新',
  748. 名称: msg.chat.title || existingGroup.group_name,
  749. 旧ID: oldGroupId,
  750. 新ID: chatIdStr,
  751. 旧类型: existingGroup.group_type,
  752. 新类型: newType,
  753. 状态: newStatus !== 'kicked' && newStatus !== 'left' ? '活跃' : '已移除'
  754. }));
  755. // 开始事务
  756. await connection.beginTransaction();
  757. try {
  758. // 检查目标ID是否已存在
  759. const [existingTargetGroup] = await connection.query(
  760. 'SELECT * FROM groups WHERE group_id = ?',
  761. [chatIdStr]
  762. );
  763. if (existingTargetGroup && existingTargetGroup.length > 0) {
  764. // 更新交易记录
  765. await connection.query(`
  766. UPDATE transactions
  767. SET group_id = ?
  768. WHERE group_id = ?
  769. `, [chatIdStr, oldGroupId]);
  770. // 更新资金记录
  771. await connection.query(`
  772. UPDATE money_records
  773. SET group_id = ?
  774. WHERE group_id = ?
  775. `, [chatIdStr, oldGroupId]);
  776. // 删除旧群组记录
  777. await connection.query(
  778. 'DELETE FROM groups WHERE group_id = ?',
  779. [oldGroupId]
  780. );
  781. // 更新目标群组信息
  782. await connection.query(`
  783. UPDATE groups
  784. SET group_type = ?,
  785. group_name = ?,
  786. is_active = ?,
  787. updated_at = CURRENT_TIMESTAMP
  788. WHERE group_id = ?
  789. `, [
  790. newType,
  791. msg.chat.title || existingGroup.group_name,
  792. newStatus !== 'kicked' && newStatus !== 'left',
  793. chatIdStr
  794. ]);
  795. } else {
  796. // 如果目标ID不存在,执行正常的更新操作
  797. // 先删除旧记录
  798. await connection.query(
  799. 'DELETE FROM groups WHERE group_id = ?',
  800. [oldGroupId]
  801. );
  802. // 插入新记录
  803. await connection.query(`
  804. INSERT INTO groups
  805. (group_id, group_name, group_type, creator_id, is_active, last_join_time)
  806. VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
  807. `, [
  808. chatIdStr,
  809. msg.chat.title || existingGroup.group_name,
  810. newType,
  811. existingGroup.creator_id,
  812. newStatus !== 'kicked' && newStatus !== 'left'
  813. ]);
  814. // 更新交易记录
  815. await connection.query(`
  816. UPDATE transactions
  817. SET group_id = ?
  818. WHERE group_id = ?
  819. `, [chatIdStr, oldGroupId]);
  820. // 更新资金记录
  821. await connection.query(`
  822. UPDATE money_records
  823. SET group_id = ?
  824. WHERE group_id = ?
  825. `, [chatIdStr, oldGroupId]);
  826. }
  827. // 提交事务
  828. await connection.commit();
  829. // 更新内存中的群组列表
  830. const index = data.allowedGroups.indexOf(oldGroupId);
  831. if (index > -1) {
  832. if (newStatus === 'kicked' || newStatus === 'left') {
  833. data.allowedGroups.splice(index, 1);
  834. } else {
  835. data.allowedGroups[index] = chatIdStr;
  836. }
  837. saveData();
  838. }
  839. } catch (error) {
  840. // 回滚事务
  841. await connection.rollback();
  842. console.error(formatLog('更新群组信息失败', error));
  843. throw error;
  844. }
  845. } else {
  846. // 如果ID没有变化,只更新其他信息
  847. await connection.query(`
  848. UPDATE groups
  849. SET group_type = ?,
  850. group_name = ?,
  851. is_active = ?,
  852. updated_at = CURRENT_TIMESTAMP
  853. WHERE group_id = ?
  854. `, [
  855. newType,
  856. msg.chat.title || existingGroup.group_name,
  857. newStatus !== 'kicked' && newStatus !== 'left',
  858. chatIdStr
  859. ]);
  860. }
  861. await connection.commit();
  862. console.log('【群组状态变更】');
  863. console.log(formatLog({
  864. ID: oldGroupId + ' -> ' + chatIdStr,
  865. type: existingGroup.group_type + ' -> ' + newType,
  866. name: existingGroup.group_name + ' -> ' + msg.chat.title || existingGroup.group_name,
  867. status: newStatus === 'kicked' || newStatus === 'left' ? '已移除' : '活跃'
  868. }));
  869. } catch (error) {
  870. await connection.rollback();
  871. console.error(formatLog({
  872. 错误: '更新群组信息失败',
  873. 详情: error.message
  874. }));
  875. throw error;
  876. } finally {
  877. connection.release();
  878. }
  879. }
  880. // 处理群组状态变更
  881. bot.on('my_chat_member', async (msg) => {
  882. try {
  883. const chatId = msg.chat.id;
  884. const newStatus = msg.new_chat_member.status;
  885. const oldStatus = msg.old_chat_member.status;
  886. const chatType = msg.chat.type;
  887. const chatIdStr = chatId.toString();
  888. // 查找群组,同时检查新旧ID
  889. const existingGroup = await Group.findByGroupId(chatIdStr) ||
  890. await Group.findByGroupId(chatIdStr.replace('-', ''));
  891. // 获取群组详细信息(如果机器人还在群组中)
  892. if (newStatus !== 'kicked' && newStatus !== 'left') {
  893. try {
  894. const chatInfo = await bot.getChat(chatId);
  895. } catch (error) {
  896. console.log(formatLog('获取群组详细信息失败', error.message));
  897. }
  898. } else {
  899. console.log('机器人已被移出群组,无法获取详细信息');
  900. }
  901. const newType = chatType === 'private' ? 'private' :
  902. chatType === 'supergroup' ? 'supergroup' : 'group';
  903. // 如果是机器人首次被添加到群组(从非成员变为成员)
  904. if (oldStatus === 'left' && newStatus === 'member' && existingGroup.group_type != newType) {
  905. await handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup);
  906. }
  907. if (existingGroup) {
  908. await handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus);
  909. }
  910. } catch (error) {
  911. console.error(formatLog({
  912. 错误: '处理群组状态变更失败',
  913. 详情: error.message
  914. }));
  915. }
  916. });
  917. // 导入公共路由
  918. const publicRoutes = require('./routes/public');
  919. // 注册公共路由
  920. app.use('/api/public', publicRoutes);
  921. // 错误处理中间件
  922. app.use((err, req, res, next) => {
  923. console.error(err.stack);
  924. res.status(500).json({ message: '服务器错误' });
  925. });
  926. // 404 处理
  927. app.use((req, res) => {
  928. res.status(404).json({ message: '未找到请求的资源' });
  929. });
  930. module.exports = app;