index.js 40 KB

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