index.js 45 KB

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