index.js 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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 checkUserPermission(chatId, userId) {
  67. try {
  68. const [group] = await pool.query(
  69. 'SELECT creator_id, COALESCE(operators, "[]") as operators FROM groups WHERE group_id = ?',
  70. [chatId.toString()]
  71. );
  72. if (!group || !group[0]) {
  73. console.log(`权限检查失败 - 群组不存在: ${chatId}`);
  74. return false;
  75. }
  76. const groupInfo = group[0];
  77. const userIdStr = userId.toString();
  78. const isCreator = groupInfo.creator_id === userIdStr;
  79. console.log(`权限检查 - 用户ID: ${userIdStr}, 创建者ID: ${groupInfo.creator_id}, 是否创建者: ${isCreator}`);
  80. let operators = [];
  81. try {
  82. if (groupInfo.operators) {
  83. operators = JSON.parse(groupInfo.operators);
  84. if (!Array.isArray(operators)) {
  85. operators = [];
  86. }
  87. }
  88. } catch (e) {
  89. console.error('解析操作人列表失败:', e);
  90. operators = [];
  91. }
  92. const isOperator = operators.some(op => {
  93. const isOp = op.operator_id === userIdStr;
  94. console.log(`检查操作人 - 操作人ID: ${op.operator_id}, 用户ID: ${userIdStr}, 是否匹配: ${isOp}`);
  95. return isOp;
  96. });
  97. console.log(`权限检查结果 - 用户ID: ${userIdStr}, 是否创建者: ${isCreator}, 是否操作人: ${isOperator}`);
  98. return isCreator || isOperator;
  99. } catch (error) {
  100. console.error('检查用户权限失败:', error);
  101. return false;
  102. }
  103. }
  104. // 处理消息发送
  105. async function sendMessage(chatId, text, options = {}) {
  106. try {
  107. // 如果包含内联键盘,验证URL
  108. if (options.reply_markup && options.reply_markup.inline_keyboard) {
  109. const keyboard = generateInlineKeyboard(chatId);
  110. if (!keyboard) {
  111. // 如果键盘无效,发送不带键盘的消息
  112. return await bot.sendMessage(chatId, text, {
  113. parse_mode: 'HTML'
  114. });
  115. }
  116. options.reply_markup = keyboard;
  117. }
  118. return await bot.sendMessage(chatId, text, {
  119. ...options,
  120. parse_mode: 'HTML'
  121. });
  122. } catch (error) {
  123. console.error('发送消息失败:', error);
  124. if (error.message.includes('bot was kicked from the group chat')) {
  125. const index = data.allowedGroups.indexOf(chatId.toString());
  126. if (index > -1) {
  127. data.allowedGroups.splice(index, 1);
  128. saveData();
  129. console.log(`群组 ${chatId} 已被移除出允许列表`);
  130. }
  131. }
  132. return null;
  133. }
  134. }
  135. // 处理快捷命令
  136. bot.on('message', async (msg) => {
  137. if (!isGroupAllowed(msg.chat.id)) return;
  138. const text = msg.text?.trim();
  139. if (!text) return;
  140. // 检查用户权限
  141. const hasPermission = await checkUserPermission(msg.chat.id, msg.from.id);
  142. console.log(`用户权限检查 - 用户ID: ${msg.from.id}, 群组ID: ${msg.chat.id}, 是否有权限: ${hasPermission}`);
  143. if (!hasPermission) {
  144. // 如果不是创建人或操作人,直接返回
  145. console.log(`用户无权限操作 - 用户ID: ${msg.from.id}, 群组ID: ${msg.chat.id}`);
  146. return;
  147. }
  148. // 处理入款命令
  149. if (text.startsWith('+')) {
  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. console.log(transactionData);
  172. try {
  173. const result = await Transaction.deposit(transactionData);
  174. if (result.success) {
  175. const billMessage = await generateBillMessage(msg.chat.id);
  176. if (billMessage) {
  177. await sendMessage(msg.chat.id, billMessage, {
  178. reply_markup: generateInlineKeyboard(msg.chat.id)
  179. });
  180. console.log(`入款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  181. } else {
  182. await sendMessage(msg.chat.id, '入款成功,但获取账单信息失败');
  183. console.log(`入款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  184. }
  185. } else {
  186. await sendMessage(msg.chat.id, result.message || '入款失败');
  187. console.log(`入款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  188. }
  189. } catch (error) {
  190. console.error('快捷入款失败:', error);
  191. await sendMessage(msg.chat.id, '记录入款失败,请稍后重试');
  192. }
  193. }
  194. }
  195. // 处理入款修正命令
  196. else if (text.startsWith('-') && !text.includes('下发')) {
  197. let amount, exchangeRate, feeRate;
  198. const parts = text.substring(1).split('/');
  199. amount = parseFloat(parts[0]);
  200. // 如果指定了汇率,则使用指定的汇率
  201. if (parts.length > 1) {
  202. exchangeRate = parseFloat(parts[1]);
  203. }
  204. // 如果指定了费率,则使用指定的费率
  205. if (parts.length > 2) {
  206. feeRate = parseFloat(parts[2]);
  207. }
  208. if (!isNaN(amount)) {
  209. const transactionData = {
  210. groupId: msg.chat.id.toString(),
  211. groupName: msg.chat.title || '未命名群组',
  212. amount: -amount,
  213. type: 'deposit',
  214. exchangeRate: exchangeRate,
  215. feeRate: feeRate,
  216. operatorId: msg.from.id
  217. };
  218. try {
  219. const result = await Transaction.deposit(transactionData);
  220. if (result.success) {
  221. const billMessage = await generateBillMessage(msg.chat.id);
  222. if (billMessage) {
  223. await sendMessage(msg.chat.id, billMessage, {
  224. reply_markup: generateInlineKeyboard(msg.chat.id)
  225. });
  226. console.log(`入款修正成功 - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  227. } else {
  228. await sendMessage(msg.chat.id, '入款修正成功,但获取账单信息失败');
  229. console.log(`入款修正成功(无账单) - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  230. }
  231. } else {
  232. await sendMessage(msg.chat.id, result.message || '入款修正失败');
  233. console.log(`入款修正失败 - 群组: ${msg.chat.title}, 金额: -${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  234. }
  235. } catch (error) {
  236. console.error('快捷入款修正失败:', error);
  237. await sendMessage(msg.chat.id, '记录入款修正失败,请稍后重试');
  238. }
  239. }
  240. }
  241. // 处理回款命令
  242. else if (text.startsWith('下发')) {
  243. let amount, exchangeRate, feeRate;
  244. const parts = text.replace(/[^0-9./-]/g, '').split('/');
  245. amount = parseFloat(parts[0]);
  246. // 如果指定了汇率,则使用指定的汇率
  247. if (parts.length > 1) {
  248. exchangeRate = parseFloat(parts[1]);
  249. }
  250. // 如果指定了费率,则使用指定的费率
  251. if (parts.length > 2) {
  252. feeRate = parseFloat(parts[2]);
  253. }
  254. if (!isNaN(amount)) {
  255. const transactionData = {
  256. groupId: msg.chat.id.toString(),
  257. groupName: msg.chat.title || '未命名群组',
  258. amount: amount,
  259. type: 'withdrawal',
  260. exchangeRate: exchangeRate,
  261. feeRate: feeRate,
  262. operatorId: msg.from.id
  263. };
  264. try {
  265. const result = await Transaction.withdrawal(transactionData);
  266. if (result.success) {
  267. const billMessage = await generateBillMessage(msg.chat.id);
  268. if (billMessage) {
  269. await sendMessage(msg.chat.id, billMessage, {
  270. reply_markup: generateInlineKeyboard(msg.chat.id)
  271. });
  272. console.log(`回款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  273. } else {
  274. await sendMessage(msg.chat.id, '回款成功,但获取账单信息失败');
  275. console.log(`回款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  276. }
  277. } else {
  278. await sendMessage(msg.chat.id, result.message || '回款失败');
  279. console.log(`回款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  280. }
  281. } catch (error) {
  282. console.error('快捷回款失败:', error);
  283. await sendMessage(msg.chat.id, '记录回款失败,请稍后重试');
  284. }
  285. }
  286. }
  287. // 处理回款修正命令
  288. else if (text.startsWith('下发-')) {
  289. let amount, exchangeRate, feeRate;
  290. const parts = text.replace(/[^0-9./-]/g, '').split('/');
  291. amount = parseFloat(parts[0]);
  292. // 如果指定了汇率,则使用指定的汇率
  293. if (parts.length > 1) {
  294. exchangeRate = parseFloat(parts[1]);
  295. }
  296. // 如果指定了费率,则使用指定的费率
  297. if (parts.length > 2) {
  298. feeRate = parseFloat(parts[2]);
  299. }
  300. if (!isNaN(amount)) {
  301. const transactionData = {
  302. groupId: msg.chat.id.toString(),
  303. groupName: msg.chat.title || '未命名群组',
  304. amount: -amount,
  305. type: 'withdrawal',
  306. exchangeRate: exchangeRate,
  307. feeRate: feeRate,
  308. operatorId: msg.from.id
  309. };
  310. try {
  311. const result = await Transaction.withdrawal(transactionData);
  312. if (result.success) {
  313. const billMessage = await generateBillMessage(msg.chat.id);
  314. if (billMessage) {
  315. await sendMessage(msg.chat.id, billMessage, {
  316. reply_markup: generateInlineKeyboard(msg.chat.id)
  317. });
  318. console.log(`回款修正成功 - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  319. } else {
  320. await sendMessage(msg.chat.id, '回款修正成功,但获取账单信息失败');
  321. console.log(`回款修正成功(无账单) - 群组: ${msg.chat.title}, 金额: -${amount}, 时间: ${new Date().toLocaleString()}`);
  322. }
  323. } else {
  324. await sendMessage(msg.chat.id, result.message || '回款修正失败');
  325. console.log(`回款修正失败 - 群组: ${msg.chat.title}, 金额: -${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  326. }
  327. } catch (error) {
  328. console.error('快捷回款修正失败:', error);
  329. await sendMessage(msg.chat.id, '记录回款修正失败,请稍后重试');
  330. }
  331. }
  332. }
  333. // 处理设置费率命令
  334. else if (text.startsWith('设置费率')) {
  335. const feeRate = parseFloat(text.replace('设置费率', '').trim());
  336. if (!isNaN(feeRate) && feeRate >= 0 && feeRate <= 100) {
  337. try {
  338. // 更新群组的入款和出款费率
  339. await pool.query(`
  340. UPDATE groups
  341. SET in_fee_rate = ?,
  342. out_fee_rate = ?,
  343. updated_at = CURRENT_TIMESTAMP
  344. WHERE group_id = ?
  345. `, [feeRate, feeRate, msg.chat.id.toString()]);
  346. await sendMessage(msg.chat.id, `费率${feeRate}%已设置成功`);
  347. console.log(`费率设置成功 - 群组: ${msg.chat.title}, 费率: ${feeRate}%, 时间: ${new Date().toLocaleString()}`);
  348. } catch (error) {
  349. console.error('设置费率失败:', error);
  350. await sendMessage(msg.chat.id, '设置费率失败,请稍后重试');
  351. }
  352. } else {
  353. await sendMessage(msg.chat.id, '费率设置失败,请输入0-100之间的数字');
  354. }
  355. }
  356. // 处理设置汇率命令
  357. else if (text.startsWith('设置汇率')) {
  358. const exchangeRate = parseFloat(text.replace('设置汇率', '').trim());
  359. if (!isNaN(exchangeRate) && exchangeRate > 0) {
  360. try {
  361. // 更新群组的入款和出款汇率
  362. await pool.query(`
  363. UPDATE groups
  364. SET in_exchange_rate = ?,
  365. out_exchange_rate = ?,
  366. updated_at = CURRENT_TIMESTAMP
  367. WHERE group_id = ?
  368. `, [exchangeRate, exchangeRate, msg.chat.id.toString()]);
  369. await sendMessage(msg.chat.id, `汇率${exchangeRate}已设置成功`);
  370. console.log(`汇率设置成功 - 群组: ${msg.chat.title}, 汇率: ${exchangeRate}, 时间: ${new Date().toLocaleString()}`);
  371. } catch (error) {
  372. console.error('设置汇率失败:', error);
  373. await sendMessage(msg.chat.id, '设置汇率失败,请稍后重试');
  374. }
  375. } else {
  376. await sendMessage(msg.chat.id, '汇率设置失败,请输入大于0的数字');
  377. }
  378. }
  379. // 处理设置操作人命令
  380. else if (text.startsWith('设置操作人')) {
  381. try {
  382. const groupId = msg.chat.id.toString();
  383. const mentionedUser = msg.entities?.find(e => e.type === 'mention');
  384. if (!mentionedUser) {
  385. // 如果没有@用户,回复原消息并提示设置用户名
  386. await bot.sendMessage(msg.chat.id, '请设置您的Telegram用户名后再试', {
  387. reply_to_message_id: msg.message_id
  388. });
  389. return;
  390. }
  391. // 获取被@的用户名
  392. const username = text.slice(mentionedUser.offset + 1, mentionedUser.offset + mentionedUser.length);
  393. // 获取群组信息
  394. const [group] = await pool.query(
  395. 'SELECT creator_id, COALESCE(operators, "[]") as operators FROM groups WHERE group_id = ?',
  396. [groupId]
  397. );
  398. if (!group || !group[0]) {
  399. await sendMessage(msg.chat.id, '群组信息不存在');
  400. return;
  401. }
  402. const groupInfo = group[0];
  403. const userId = msg.from.id.toString();
  404. // 检查操作权限(群组创建者或现有操作人)
  405. const isCreator = groupInfo.creator_id === userId;
  406. let operators = [];
  407. try {
  408. if (groupInfo.operators) {
  409. operators = JSON.parse(groupInfo.operators);
  410. if (!Array.isArray(operators)) {
  411. operators = [];
  412. }
  413. }
  414. } catch (e) {
  415. console.error('解析操作人列表失败:', e);
  416. operators = [];
  417. }
  418. const isOperator = operators.some(op => op.operator_id === userId);
  419. if (!isCreator && !isOperator) {
  420. await sendMessage(msg.chat.id, '您没有权限设置操作人');
  421. return;
  422. }
  423. // 获取被@用户的ID
  424. const [user] = await pool.query(
  425. 'SELECT id FROM users WHERE username = ?',
  426. [username]
  427. );
  428. let newOperatorId;
  429. if (!user || !user[0]) {
  430. // 如果用户不存在,创建新用户
  431. try {
  432. const [result] = await pool.query(
  433. 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)',
  434. [username, '', 'user']
  435. );
  436. newOperatorId = result.insertId.toString();
  437. console.log(`创建新用户成功 - 用户名: ${username}, ID: ${newOperatorId}`);
  438. } catch (error) {
  439. console.error('创建新用户失败:', error);
  440. await sendMessage(msg.chat.id, '创建用户失败,请稍后重试');
  441. return;
  442. }
  443. } else {
  444. newOperatorId = user[0].id.toString();
  445. }
  446. // 检查是否已经是操作人
  447. if (operators.some(op => op.operator_id === newOperatorId)) {
  448. await sendMessage(msg.chat.id, '该用户已经是操作人');
  449. return;
  450. }
  451. // 添加新操作人
  452. operators.push({
  453. operator_id: newOperatorId,
  454. operator_username: username,
  455. added_by: userId,
  456. added_at: new Date().toISOString()
  457. });
  458. // 更新群组
  459. await pool.query(
  460. 'UPDATE groups SET operators = ? WHERE group_id = ?',
  461. [JSON.stringify(operators), groupId]
  462. );
  463. await sendMessage(msg.chat.id, `已成功设置 @${username} 为操作人`);
  464. console.log(`设置操作人成功 - 群组: ${msg.chat.title}, 新操作人: ${username}, 设置者: ${msg.from.username || msg.from.first_name}, 时间: ${new Date().toLocaleString()}`);
  465. } catch (error) {
  466. console.error('设置操作人失败:', error);
  467. if (error.code === 'ER_BAD_FIELD_ERROR') {
  468. await sendMessage(msg.chat.id, '系统正在升级,请稍后再试');
  469. } else {
  470. await sendMessage(msg.chat.id, '设置操作人失败,请稍后重试');
  471. }
  472. }
  473. }
  474. // 处理TRX地址
  475. else if (/^T[A-Za-z0-9]{33}$/.test(text)) {
  476. try {
  477. const groupId = msg.chat.id.toString();
  478. // 检查地址是否已存在
  479. const [existingAddress] = await pool.query(
  480. 'SELECT * FROM trx_addresses WHERE address = ? AND group_id = ?',
  481. [text, groupId]
  482. );
  483. if (existingAddress && existingAddress.length > 0) {
  484. // 更新使用次数和最后出现时间
  485. await pool.query(`
  486. UPDATE trx_addresses
  487. SET usage_count = usage_count + 1,
  488. last_seen_time = CURRENT_TIMESTAMP
  489. WHERE address = ? AND group_id = ?
  490. `, [text, groupId]);
  491. const newCount = existingAddress[0].usage_count + 1;
  492. await sendMessage(msg.chat.id, `此地址累计发送第${newCount}次`);
  493. console.log(`TRX地址使用次数更新 - 群组: ${msg.chat.title}, 地址: ${text}, 次数: ${newCount}, 时间: ${new Date().toLocaleString()}`);
  494. } else {
  495. // 插入新地址记录
  496. await pool.query(`
  497. INSERT INTO trx_addresses (address, group_id)
  498. VALUES (?, ?)
  499. `, [text, groupId]);
  500. await sendMessage(msg.chat.id, '此地址累计发送第1次');
  501. console.log(`新TRX地址记录 - 群组: ${msg.chat.title}, 地址: ${text}, 时间: ${new Date().toLocaleString()}`);
  502. }
  503. } catch (error) {
  504. console.error('处理TRX地址失败:', error);
  505. await sendMessage(msg.chat.id, '处理地址失败,请稍后重试');
  506. }
  507. }
  508. });
  509. // 处理新成员加入
  510. bot.on('new_chat_members', async (msg) => {
  511. const chatId = msg.chat.id;
  512. const newMembers = msg.new_chat_members;
  513. for (const member of newMembers) {
  514. if (member.id === (await bot.getMe()).id) {
  515. // 检查群组是否在允许列表中
  516. const chatIdStr = chatId.toString();
  517. try {
  518. // 先检查数据库中是否存在该群组
  519. const existingGroup = await Group.findByGroupId(chatIdStr);
  520. // 检查邀请者是否已存在于用户表中
  521. const [existingUser] = await pool.query(
  522. 'SELECT * FROM users WHERE id = ?',
  523. [msg.from.id]
  524. );
  525. // 如果用户不存在,则创建新用户
  526. if (!existingUser || existingUser.length === 0) {
  527. // 生成唯一的用户名
  528. const username = msg.from.username || `user_${msg.from.id}`;
  529. await pool.query(`
  530. INSERT INTO users
  531. (id, username, password, role)
  532. VALUES (?, ?, '', 'user')
  533. `, [msg.from.id, username]);
  534. console.log(formatLog({
  535. 操作: '新增用户',
  536. ID: msg.from.id,
  537. 用户名: username,
  538. 角色: 'user',
  539. 时间: new Date().toLocaleString()
  540. }));
  541. }
  542. if (existingGroup) {
  543. // 如果群组存在,更新群组状态为活跃,同时更新群组名称和加入时间
  544. await pool.query(`
  545. UPDATE groups
  546. SET is_active = true,
  547. group_name = ?,
  548. last_join_time = CURRENT_TIMESTAMP
  549. WHERE group_id = ?
  550. `, [msg.chat.title || existingGroup.group_name, chatIdStr]);
  551. // 更新内存中的群组列表
  552. if (!data.allowedGroups.includes(chatIdStr)) {
  553. data.allowedGroups.push(chatIdStr);
  554. saveData();
  555. }
  556. // 发送欢迎消息并显示当前账单
  557. await sendMessage(chatId, '感谢重新添加我为群组成员!');
  558. const billMessage = await generateBillMessage(chatId);
  559. if (billMessage) {
  560. await sendMessage(chatId, billMessage, {
  561. reply_markup: generateInlineKeyboard(chatId)
  562. });
  563. }
  564. } else {
  565. // 如果是新群组,打印被添加到新群组的信息
  566. console.log(formatLog({
  567. ID: chatId,
  568. 名称: msg.chat.title || '未命名群组',
  569. 类型: msg.chat.type,
  570. 描述: msg.chat.description || '无',
  571. '添加者信息': {
  572. ID: msg.from.id,
  573. 用户名: msg.from.username || '无',
  574. 姓名: msg.from.first_name,
  575. ...(msg.from.last_name && {
  576. 姓: msg.from.last_name
  577. })
  578. },
  579. 添加时间: new Date().toLocaleString()
  580. }));
  581. // 如果群组不存在,创建新群组
  582. const groupData = {
  583. groupId: chatIdStr,
  584. groupName: msg.chat.title || '未命名群组',
  585. groupType: msg.chat.type === 'private' ? 'personal' : msg.chat.type,
  586. creatorId: msg.from.id.toString()
  587. };
  588. console.log(formatLog(groupData));
  589. try {
  590. // 直接使用 SQL 插入或更新群组数据
  591. const [result] = await pool.query(`
  592. INSERT INTO groups
  593. (group_id, group_name, group_type, creator_id, is_active, last_join_time,
  594. in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate, operators)
  595. VALUES (?, ?, ?, ?, true, CURRENT_TIMESTAMP, 0.00, 1.0000, 0.00, 1.0000, '[]')
  596. ON DUPLICATE KEY UPDATE
  597. group_name = VALUES(group_name),
  598. group_type = VALUES(group_type),
  599. is_active = true,
  600. last_join_time = CURRENT_TIMESTAMP
  601. `, [
  602. groupData.groupId,
  603. groupData.groupName,
  604. groupData.groupType,
  605. groupData.creatorId
  606. ]);
  607. console.log(formatLog(result));
  608. // 更新内存中的群组列表
  609. if (!data.allowedGroups.includes(chatIdStr)) {
  610. data.allowedGroups.push(chatIdStr);
  611. saveData();
  612. console.log(formatLog({
  613. ID: chatIdStr,
  614. 名称: groupData.groupName,
  615. 类型: groupData.groupType,
  616. 状态: '已启用',
  617. 添加时间: new Date().toLocaleString(),
  618. 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  619. }));
  620. }
  621. console.log(formatLog({
  622. ID: chatIdStr,
  623. 名称: groupData.groupName,
  624. 类型: groupData.groupType,
  625. 状态: '已启用',
  626. 添加时间: new Date().toLocaleString(),
  627. 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  628. }));
  629. try {
  630. // 尝试发送欢迎消息
  631. const welcomeMessage = await bot.sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。', {
  632. parse_mode: 'HTML'
  633. });
  634. console.log(formatLog(welcomeMessage));
  635. // 尝试发送账单消息
  636. const billMessage = await generateBillMessage(chatId);
  637. if (billMessage) {
  638. const billResult = await bot.sendMessage(chatId, billMessage, {
  639. parse_mode: 'HTML',
  640. reply_markup: generateInlineKeyboard(chatId)
  641. });
  642. console.log(formatLog(billResult));
  643. }
  644. } catch (messageError) {
  645. console.error(formatLog(messageError));
  646. }
  647. } catch (error) {
  648. console.error(formatLog('创建群组过程中出错', error));
  649. try {
  650. await bot.sendMessage(chatId, '添加群组失败,请联系管理员。', {
  651. parse_mode: 'HTML'
  652. });
  653. } catch (messageError) {
  654. console.error(formatLog('发送错误消息失败', messageError));
  655. }
  656. }
  657. }
  658. } catch (error) {
  659. console.error(formatLog('处理群组加入失败', error));
  660. await sendMessage(chatId, '添加群组失败,请联系管理员。');
  661. }
  662. } else {
  663. // 其他新成员
  664. console.log(formatLog({
  665. member: member.username || member.first_name + ' (' + member.id + ')'
  666. }));
  667. await sendMessage(chatId, `欢迎 ${member.username || member.first_name} 加入群组!`);
  668. }
  669. }
  670. });
  671. // 处理机器人被移出群组
  672. bot.on('left_chat_member', async (msg) => {
  673. if (msg.left_chat_member.id === (await bot.getMe()).id) {
  674. const chatId = msg.chat.id.toString();
  675. try {
  676. // 更新数据库中的群组状态
  677. await pool.query(`
  678. UPDATE groups
  679. SET is_active = false,
  680. last_leave_time = CURRENT_TIMESTAMP
  681. WHERE group_id = ?
  682. `, [chatId]);
  683. // 从内存中的允许列表中移除
  684. const index = data.allowedGroups.indexOf(chatId);
  685. if (index > -1) {
  686. data.allowedGroups.splice(index, 1);
  687. saveData();
  688. }
  689. // console.log(formatLog({
  690. // ID: chatId,
  691. // 名称: msg.chat.title || '未命名群组',
  692. // 类型: msg.chat.type,
  693. // 状态: '已移除',
  694. // 移除时间: new Date().toLocaleString(),
  695. // 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  696. // }));
  697. } catch (error) {
  698. console.error(formatLog('处理机器人被移出群组失败', error));
  699. }
  700. }
  701. });
  702. // 处理管理员命令
  703. bot.onText(/\/addgroup (.+)/, async (msg, match) => {
  704. if (!isAdmin(msg.from.id)) {
  705. sendMessage(msg.chat.id, '您没有权限执行此命令。');
  706. return;
  707. }
  708. const groupId = match[1].trim();
  709. if (!data.allowedGroups.includes(groupId)) {
  710. try {
  711. // 使用 createGroup 创建新群组
  712. const groupData = {
  713. groupId: groupId,
  714. groupName: '手动添加的群组',
  715. groupType: 'public',
  716. creatorId: msg.from.id.toString()
  717. };
  718. const result = await createGroup({
  719. body: groupData
  720. });
  721. if (result) {
  722. data.allowedGroups.push(groupId);
  723. saveData();
  724. console.log(formatLog({
  725. ID: groupId,
  726. 名称: groupData.groupName,
  727. 状态: '已启用',
  728. 添加时间: new Date().toLocaleString(),
  729. 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  730. }));
  731. sendMessage(msg.chat.id, `群组 ${groupId} 已添加到允许列表。`);
  732. } else {
  733. sendMessage(msg.chat.id, '添加群组失败,请检查群组ID是否正确。');
  734. }
  735. } catch (error) {
  736. console.error(formatLog('创建群组失败', error));
  737. sendMessage(msg.chat.id, '添加群组失败,请稍后重试。');
  738. }
  739. } else {
  740. sendMessage(msg.chat.id, '该群组已在允许列表中。');
  741. }
  742. });
  743. // 处理查看账单命令
  744. bot.onText(/\/bill/, async (msg) => {
  745. const billMessage = await generateBillMessage(msg.chat.id);
  746. sendMessage(msg.chat.id, billMessage, {
  747. reply_markup: generateInlineKeyboard(msg.chat.id)
  748. });
  749. });
  750. // 更新帮助命令
  751. bot.onText(/\/help/, (msg) => {
  752. const helpMessage = `
  753. 🤖 机器人使用指南
  754. 📝 基础命令
  755. • /deposit 数字 - 记录入款
  756. • /withdraw 数字 - 记录下发
  757. • /bill - 查看当前账单
  758. • /help - 显示此帮助信息
  759. ⚡️ 快捷命令
  760. • +数字 - 快速记录入款(例如:+2000)
  761. • -数字 - 快速记录下发(例如:-2000)
  762. 👨‍💼 管理员命令
  763. • /addgroup 群组ID - 添加允许的群组
  764. • /removegroup 群组ID - 移除允许的群组
  765. • /listgroups - 列出所有允许的群组
  766. 💡 使用提示
  767. • 所有金额输入请使用数字
  768. • 账单信息实时更新
  769. • 如需帮助请联系管理员
  770. `;
  771. sendMessage(msg.chat.id, helpMessage);
  772. });
  773. // 生成账单消息
  774. async function generateBillMessage(chatId) {
  775. try {
  776. // 获取群组的最后加入时间和费率信息
  777. const [groupInfo] = await pool.query(
  778. 'SELECT last_join_time, in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate FROM groups WHERE group_id = ?',
  779. [chatId.toString()]
  780. );
  781. if (!groupInfo || groupInfo.length === 0) {
  782. return '暂无交易记录';
  783. }
  784. const lastJoinTime = groupInfo[0].last_join_time;
  785. const inFeeRate = parseFloat(groupInfo[0].in_fee_rate) || 0;
  786. const inExchangeRate = parseFloat(groupInfo[0].in_exchange_rate) || 0;
  787. const outFeeRate = parseFloat(groupInfo[0].out_fee_rate) || 0;
  788. const outExchangeRate = parseFloat(groupInfo[0].out_exchange_rate) || 0;
  789. // 获取机器人加入后的交易记录
  790. const [records] = await pool.query(`
  791. SELECT t.*,
  792. COALESCE(t.fee_rate, g.in_fee_rate) as fee_rate,
  793. COALESCE(t.exchange_rate, g.in_exchange_rate) as exchange_rate
  794. FROM transactions t
  795. LEFT JOIN groups g ON t.group_id = g.group_id
  796. WHERE t.group_id = ?
  797. AND DATE(t.time) = CURDATE()
  798. ORDER BY t.time DESC
  799. `, [chatId.toString()]);
  800. if (!records || records.length === 0) {
  801. return '暂无交易记录';
  802. }
  803. const deposits = records.filter(r => r.type === 'deposit');
  804. const withdrawals = records.filter(r => r.type === 'withdrawal');
  805. const totalDeposit = deposits.reduce((sum, d) => sum + parseFloat(d.amount), 0);
  806. const totalWithdrawal = withdrawals.reduce((sum, w) => sum + parseFloat(w.amount), 0);
  807. const depositFee = totalDeposit * (inFeeRate / 100);
  808. const withdrawalFee = totalWithdrawal * (outFeeRate / 100);
  809. const remaining = totalDeposit - depositFee - totalWithdrawal - withdrawalFee;
  810. const remainingU = (remaining / inExchangeRate).toFixed(2);
  811. // 获取当前日期
  812. const today = new Date();
  813. const version = 'v29';
  814. const dateStr = today.toISOString().split('T')[0].replace(/-/g, '-');
  815. let message = `当前版本:<b>${dateStr}:${version}</b>\n\n`;
  816. // 添加入款记录
  817. if (deposits.length > 0) {
  818. message += `<b>入款笔数</b>:<code>${deposits.length}</code>\n`;
  819. deposits.forEach(deposit => {
  820. message += `<code>${moment(deposit.time).format('HH:mm:ss')} ${parseFloat(deposit.amount).toFixed(2)}</code>\n`;
  821. });
  822. message += '\n';
  823. } else {
  824. message += `<b>入款笔数</b>:<code>0</code>\n\n`;
  825. }
  826. // 添加出款记录
  827. if (withdrawals.length > 0) {
  828. message += `<b>出款笔数</b>:<code>${withdrawals.length}</code>\n`;
  829. withdrawals.forEach(withdrawal => {
  830. message += `<code>${moment(withdrawal.time).format('HH:mm:ss')} ${parseFloat(withdrawal.amount).toFixed(2)}</code>\n`;
  831. });
  832. message += '\n';
  833. } else {
  834. message += `<b>出款笔数</b>:<code>0</code>\n\n`;
  835. }
  836. // 添加费率信息
  837. message += `<b>入款费率</b>:<code>${inFeeRate}%</code>\n`;
  838. message += `<b>入款汇率</b>:<code>${inExchangeRate}</code>\n`;
  839. message += `<b>入款总额</b>:<code>${totalDeposit.toFixed(2)}</code>\n`;
  840. message += `<b>入款合计</b>:<code>${(totalDeposit - depositFee).toFixed(2)}|${((totalDeposit - depositFee) / inExchangeRate).toFixed(2)}U</code>\n\n`;
  841. message += `<b>出款费率</b>:<code>${outFeeRate}%</code>\n`;
  842. message += `<b>出款汇率</b>:<code>${outExchangeRate}</code>\n`;
  843. message += `<b>出款总额</b>:<code>${totalWithdrawal.toFixed(2)}</code>\n`;
  844. message += `<b>出款合计</b>:<code>${(totalWithdrawal - withdrawalFee).toFixed(2)}|${((totalWithdrawal - withdrawalFee) / outExchangeRate).toFixed(2)}U</code>\n\n`;
  845. // 添加余额信息
  846. message += `<b>应下发</b>:<code>${remainingU}U</code>\n`;
  847. message += `<b>已下发</b>:<code>${(totalWithdrawal / outExchangeRate).toFixed(2)}U</code>\n`;
  848. message += `<b>未下发</b>:<code>${(remainingU - (totalWithdrawal / outExchangeRate)).toFixed(2)}U</code>`;
  849. return message;
  850. } catch (error) {
  851. console.error(formatLog('生成账单消息失败', error));
  852. return '获取账单信息失败,请稍后重试';
  853. }
  854. }
  855. // 生成内联键盘
  856. function generateInlineKeyboard(chatId) {
  857. const keyboard = {
  858. inline_keyboard: [
  859. [{
  860. text: '点击跳转完整账单',
  861. callback_data: `bill_page_${chatId}`
  862. }],
  863. [{
  864. text: '24小时商务对接',
  865. callback_data: 'business_contact'
  866. }]
  867. ]
  868. };
  869. return keyboard;
  870. }
  871. // 处理内联按钮回调
  872. bot.on('callback_query', async (callbackQuery) => {
  873. const chatId = callbackQuery.message.chat.id;
  874. const data = callbackQuery.data;
  875. try {
  876. if (data.startsWith('bill_page_')) {
  877. const groupId = data.split('_')[2];
  878. await bot.answerCallbackQuery(callbackQuery.id, {
  879. url: 'https://google.com'
  880. });
  881. } else if (data === 'business_contact') {
  882. await bot.answerCallbackQuery(callbackQuery.id, {
  883. url: 'https://t.me/your_business_account'
  884. });
  885. }
  886. } catch (error) {
  887. console.error(formatLog('处理内联按钮回调失败', error));
  888. await bot.answerCallbackQuery(callbackQuery.id, {
  889. text: '操作失败,请稍后重试',
  890. show_alert: true
  891. });
  892. }
  893. });
  894. // 保存数据
  895. function saveData() {
  896. try {
  897. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  898. } catch (error) {
  899. console.error(formatLog('Error saving data', error));
  900. }
  901. }
  902. // 加载数据
  903. function loadData() {
  904. try {
  905. if (fs.existsSync(process.env.DB_FILE)) {
  906. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  907. data = {
  908. ...data,
  909. ...savedData
  910. };
  911. }
  912. } catch (error) {
  913. console.error(formatLog('Error loading data', error));
  914. }
  915. }
  916. // 测试数据库连接并初始化
  917. testConnection().then(() => {
  918. return initDatabase();
  919. }).then(() => {
  920. // 加载数据
  921. loadData();
  922. // 启动服务器
  923. const PORT = process.env.PORT || 3000;
  924. app.listen(PORT, () => {
  925. console.log(formatLog({
  926. PORT: PORT
  927. }));
  928. console.log('机器人已准备就绪!');
  929. });
  930. }).catch(error => {
  931. console.error(formatLog('启动失败', error));
  932. process.exit(1);
  933. });
  934. // 处理机器人被添加到群组
  935. async function handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup) {
  936. try {
  937. // 获取群组链接
  938. const chatInfo = await bot.getChat(chatId);
  939. const groupInfo = {
  940. ID: chatId,
  941. 名称: msg.chat.title || '未命名群组',
  942. 类型: chatType,
  943. 状态: existingGroup ? '重新激活' : '已激活',
  944. 群组链接: chatInfo.invite_link || '未设置',
  945. 更新时间: new Date().toLocaleString()
  946. };
  947. // 如果群组不存在,创建新群组
  948. if (!existingGroup) {
  949. const groupData = {
  950. groupId: chatIdStr,
  951. groupName: msg.chat.title || '未命名群组',
  952. groupType: chatType === 'private' ? 'personal' : chatType,
  953. creatorId: msg.from.id.toString()
  954. };
  955. try {
  956. // 直接使用 SQL 插入或更新群组数据
  957. const [result] = await pool.query(`
  958. INSERT INTO groups
  959. (group_id, group_name, group_type, creator_id, is_active, last_join_time,
  960. in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate, operators)
  961. VALUES (?, ?, ?, ?, true, CURRENT_TIMESTAMP, 0.00, 1.0000, 0.00, 1.0000, '[]')
  962. ON DUPLICATE KEY UPDATE
  963. group_name = VALUES(group_name),
  964. group_type = VALUES(group_type),
  965. is_active = true,
  966. last_join_time = CURRENT_TIMESTAMP
  967. `, [
  968. groupData.groupId,
  969. groupData.groupName,
  970. groupData.groupType,
  971. groupData.creatorId
  972. ]);
  973. // 更新内存中的群组列表
  974. if (!data.allowedGroups.includes(chatIdStr)) {
  975. data.allowedGroups.push(chatIdStr);
  976. saveData();
  977. console.log(`群组已添加 - ID: ${chatIdStr}, 名称: ${groupData.groupName}`);
  978. }
  979. try {
  980. // 发送欢迎消息
  981. await bot.sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。', {
  982. parse_mode: 'HTML'
  983. });
  984. // 发送账单消息
  985. const billMessage = await generateBillMessage(chatId);
  986. if (billMessage) {
  987. await bot.sendMessage(chatId, billMessage, {
  988. parse_mode: 'HTML',
  989. reply_markup: generateInlineKeyboard(chatId)
  990. });
  991. }
  992. } catch (messageError) {
  993. console.error('发送消息失败:', messageError.message);
  994. }
  995. } catch (error) {
  996. console.error('创建群组失败:', {
  997. 错误: error.message,
  998. 群组ID: groupData.groupId
  999. });
  1000. try {
  1001. await bot.sendMessage(chatId, '添加群组失败,请联系管理员。', {
  1002. parse_mode: 'HTML'
  1003. });
  1004. } catch (messageError) {
  1005. console.error('发送错误消息失败:', messageError.message);
  1006. }
  1007. }
  1008. }
  1009. } catch (error) {
  1010. console.error('处理群组添加失败:', error.message);
  1011. await sendMessage(chatId, '添加群组失败,请联系管理员。');
  1012. }
  1013. }
  1014. // 处理群组信息更新
  1015. async function handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus) {
  1016. const connection = await pool.getConnection();
  1017. await connection.beginTransaction();
  1018. try {
  1019. // 更新群组ID和类型
  1020. const newType = chatType === 'private' ? 'private' :
  1021. chatType === 'supergroup' ? 'supergroup' : 'group';
  1022. const oldGroupId = existingGroup.group_id;
  1023. // 如果群组ID发生变化,更新所有相关记录
  1024. if (existingGroup.group_type != newType) {
  1025. console.log(formatLog({
  1026. 操作: '群组类型更新',
  1027. 名称: msg.chat.title || existingGroup.group_name,
  1028. 旧ID: oldGroupId,
  1029. 新ID: chatIdStr,
  1030. 旧类型: existingGroup.group_type,
  1031. 新类型: newType,
  1032. 状态: newStatus !== 'kicked' && newStatus !== 'left' ? '活跃' : '已移除'
  1033. }));
  1034. // 开始事务
  1035. await connection.beginTransaction();
  1036. try {
  1037. // 检查目标ID是否已存在
  1038. const [existingTargetGroup] = await connection.query(
  1039. 'SELECT * FROM groups WHERE group_id = ?',
  1040. [chatIdStr]
  1041. );
  1042. if (existingTargetGroup && existingTargetGroup.length > 0) {
  1043. // 更新交易记录
  1044. await connection.query(`
  1045. UPDATE transactions
  1046. SET group_id = ?
  1047. WHERE group_id = ?
  1048. `, [chatIdStr, oldGroupId]);
  1049. // 更新资金记录
  1050. await connection.query(`
  1051. UPDATE money_records
  1052. SET group_id = ?
  1053. WHERE group_id = ?
  1054. `, [chatIdStr, oldGroupId]);
  1055. // 删除旧群组记录
  1056. await connection.query(
  1057. 'DELETE FROM groups WHERE group_id = ?',
  1058. [oldGroupId]
  1059. );
  1060. // 更新目标群组信息
  1061. await connection.query(`
  1062. UPDATE groups
  1063. SET group_type = ?,
  1064. group_name = ?,
  1065. is_active = ?,
  1066. updated_at = CURRENT_TIMESTAMP
  1067. WHERE group_id = ?
  1068. `, [
  1069. newType,
  1070. msg.chat.title || existingGroup.group_name,
  1071. newStatus !== 'kicked' && newStatus !== 'left',
  1072. chatIdStr
  1073. ]);
  1074. } else {
  1075. // 如果目标ID不存在,执行正常的更新操作
  1076. // 先删除旧记录
  1077. await connection.query(
  1078. 'DELETE FROM groups WHERE group_id = ?',
  1079. [oldGroupId]
  1080. );
  1081. // 插入新记录
  1082. await connection.query(`
  1083. INSERT INTO groups
  1084. (group_id, group_name, group_type, creator_id, is_active, last_join_time)
  1085. VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
  1086. `, [
  1087. chatIdStr,
  1088. msg.chat.title || existingGroup.group_name,
  1089. newType,
  1090. existingGroup.creator_id,
  1091. newStatus !== 'kicked' && newStatus !== 'left'
  1092. ]);
  1093. // 更新交易记录
  1094. await connection.query(`
  1095. UPDATE transactions
  1096. SET group_id = ?
  1097. WHERE group_id = ?
  1098. `, [chatIdStr, oldGroupId]);
  1099. // 更新资金记录
  1100. await connection.query(`
  1101. UPDATE money_records
  1102. SET group_id = ?
  1103. WHERE group_id = ?
  1104. `, [chatIdStr, oldGroupId]);
  1105. }
  1106. // 提交事务
  1107. await connection.commit();
  1108. // 更新内存中的群组列表
  1109. const index = data.allowedGroups.indexOf(oldGroupId);
  1110. if (index > -1) {
  1111. if (newStatus === 'kicked' || newStatus === 'left') {
  1112. data.allowedGroups.splice(index, 1);
  1113. } else {
  1114. data.allowedGroups[index] = chatIdStr;
  1115. }
  1116. saveData();
  1117. }
  1118. } catch (error) {
  1119. // 回滚事务
  1120. await connection.rollback();
  1121. console.error(formatLog('更新群组信息失败', error));
  1122. throw error;
  1123. }
  1124. } else {
  1125. // 如果ID没有变化,只更新其他信息
  1126. await connection.query(`
  1127. UPDATE groups
  1128. SET group_type = ?,
  1129. group_name = ?,
  1130. is_active = ?,
  1131. updated_at = CURRENT_TIMESTAMP
  1132. WHERE group_id = ?
  1133. `, [
  1134. newType,
  1135. msg.chat.title || existingGroup.group_name,
  1136. newStatus !== 'kicked' && newStatus !== 'left',
  1137. chatIdStr
  1138. ]);
  1139. }
  1140. await connection.commit();
  1141. console.log('【群组状态变更】');
  1142. console.log(formatLog({
  1143. ID: oldGroupId + ' -> ' + chatIdStr,
  1144. type: existingGroup.group_type + ' -> ' + newType,
  1145. name: existingGroup.group_name + ' -> ' + msg.chat.title || existingGroup.group_name,
  1146. status: newStatus === 'kicked' || newStatus === 'left' ? '已移除' : '活跃'
  1147. }));
  1148. } catch (error) {
  1149. await connection.rollback();
  1150. console.error(formatLog({
  1151. 错误: '更新群组信息失败',
  1152. 详情: error.message
  1153. }));
  1154. throw error;
  1155. } finally {
  1156. connection.release();
  1157. }
  1158. }
  1159. // 处理群组状态变更
  1160. bot.on('my_chat_member', async (msg) => {
  1161. try {
  1162. const chatId = msg.chat.id;
  1163. const newStatus = msg.new_chat_member.status;
  1164. const oldStatus = msg.old_chat_member.status;
  1165. const chatType = msg.chat.type;
  1166. const chatIdStr = chatId.toString();
  1167. // 查找群组,同时检查新旧ID
  1168. const existingGroup = await Group.findByGroupId(chatIdStr) ||
  1169. await Group.findByGroupId(chatIdStr.replace('-', ''));
  1170. // 获取群组详细信息(如果机器人还在群组中)
  1171. if (newStatus !== 'kicked' && newStatus !== 'left') {
  1172. try {
  1173. const chatInfo = await bot.getChat(chatId);
  1174. } catch (error) {
  1175. console.log(formatLog('获取群组详细信息失败', error.message));
  1176. }
  1177. } else {
  1178. console.log('机器人已被移出群组,无法获取详细信息');
  1179. }
  1180. const newType = chatType === 'private' ? 'private' :
  1181. chatType === 'supergroup' ? 'supergroup' : 'group';
  1182. // 如果是机器人首次被添加到群组(从非成员变为成员)
  1183. if (oldStatus === 'left' && newStatus === 'member') {
  1184. if (!existingGroup) {
  1185. await handleBotAdded(msg, chatId, chatType, chatIdStr, null);
  1186. } else if (existingGroup.group_type !== newType) {
  1187. await handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup);
  1188. }
  1189. }
  1190. if (existingGroup) {
  1191. await handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus);
  1192. } else if (newStatus === 'member') {
  1193. // 如果是新群组且机器人被添加为成员
  1194. await handleBotAdded(msg, chatId, chatType, chatIdStr, null);
  1195. }
  1196. } catch (error) {
  1197. console.error(formatLog({
  1198. 错误: '处理群组状态变更失败',
  1199. 详情: error.message
  1200. }));
  1201. }
  1202. });
  1203. // 导入公共路由
  1204. const publicRoutes = require('./routes/public');
  1205. // 注册公共路由
  1206. app.use('/api/public', publicRoutes);
  1207. // 错误处理中间件
  1208. app.use((err, req, res, next) => {
  1209. console.error(err.stack);
  1210. res.status(500).json({ message: '服务器错误' });
  1211. });
  1212. // 404 处理
  1213. app.use((req, res) => {
  1214. res.status(404).json({ message: '未找到请求的资源' });
  1215. });
  1216. module.exports = app;