index.js 43 KB

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