index.js 41 KB

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