index.js 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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('left_chat_member', async (msg) => {
  511. if (msg.left_chat_member.id === (await bot.getMe()).id) {
  512. const chatId = msg.chat.id.toString();
  513. try {
  514. // 更新数据库中的群组状态
  515. await pool.query(`
  516. UPDATE groups
  517. SET is_active = false,
  518. last_leave_time = CURRENT_TIMESTAMP
  519. WHERE group_id = ?
  520. `, [chatId]);
  521. // 从内存中的允许列表中移除
  522. const index = data.allowedGroups.indexOf(chatId);
  523. if (index > -1) {
  524. data.allowedGroups.splice(index, 1);
  525. saveData();
  526. }
  527. // console.log(formatLog({
  528. // ID: chatId,
  529. // 名称: msg.chat.title || '未命名群组',
  530. // 类型: msg.chat.type,
  531. // 状态: '已移除',
  532. // 移除时间: new Date().toLocaleString(),
  533. // 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  534. // }));
  535. } catch (error) {
  536. console.error(formatLog('处理机器人被移出群组失败', error));
  537. }
  538. }
  539. });
  540. // 处理管理员命令
  541. bot.onText(/\/addgroup (.+)/, async (msg, match) => {
  542. if (!isAdmin(msg.from.id)) {
  543. sendMessage(msg.chat.id, '您没有权限执行此命令。');
  544. return;
  545. }
  546. const groupId = match[1].trim();
  547. if (!data.allowedGroups.includes(groupId)) {
  548. try {
  549. // 使用 createGroup 创建新群组
  550. const groupData = {
  551. groupId: groupId,
  552. groupName: '手动添加的群组',
  553. groupType: 'public',
  554. creatorId: msg.from.id.toString()
  555. };
  556. const result = await createGroup({
  557. body: groupData
  558. });
  559. if (result) {
  560. data.allowedGroups.push(groupId);
  561. saveData();
  562. console.log(formatLog({
  563. ID: groupId,
  564. 名称: groupData.groupName,
  565. 状态: '已启用',
  566. 添加时间: new Date().toLocaleString(),
  567. 操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
  568. }));
  569. sendMessage(msg.chat.id, `群组 ${groupId} 已添加到允许列表。`);
  570. } else {
  571. sendMessage(msg.chat.id, '添加群组失败,请检查群组ID是否正确。');
  572. }
  573. } catch (error) {
  574. console.error(formatLog('创建群组失败', error));
  575. sendMessage(msg.chat.id, '添加群组失败,请稍后重试。');
  576. }
  577. } else {
  578. sendMessage(msg.chat.id, '该群组已在允许列表中。');
  579. }
  580. });
  581. // 处理查看账单命令
  582. bot.onText(/\/bill/, async (msg) => {
  583. const billMessage = await generateBillMessage(msg.chat.id);
  584. sendMessage(msg.chat.id, billMessage, {
  585. reply_markup: generateInlineKeyboard(msg.chat.id)
  586. });
  587. });
  588. // 更新帮助命令
  589. bot.onText(/\/help/, (msg) => {
  590. const helpMessage = `
  591. 🤖 机器人使用指南
  592. 📝 基础命令
  593. • /deposit 数字 - 记录入款
  594. • /withdraw 数字 - 记录下发
  595. • /bill - 查看当前账单
  596. • /help - 显示此帮助信息
  597. ⚡️ 快捷命令
  598. • +数字 - 快速记录入款(例如:+2000)
  599. • -数字 - 快速记录下发(例如:-2000)
  600. 👨‍💼 管理员命令
  601. • /addgroup 群组ID - 添加允许的群组
  602. • /removegroup 群组ID - 移除允许的群组
  603. • /listgroups - 列出所有允许的群组
  604. 💡 使用提示
  605. • 所有金额输入请使用数字
  606. • 账单信息实时更新
  607. • 如需帮助请联系管理员
  608. `;
  609. sendMessage(msg.chat.id, helpMessage);
  610. });
  611. // 生成账单消息
  612. async function generateBillMessage(chatId) {
  613. try {
  614. // 获取群组的最后加入时间和费率信息
  615. const [groupInfo] = await pool.query(
  616. 'SELECT last_join_time, in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate FROM groups WHERE group_id = ?',
  617. [chatId.toString()]
  618. );
  619. if (!groupInfo || groupInfo.length === 0) {
  620. return '暂无交易记录';
  621. }
  622. const lastJoinTime = groupInfo[0].last_join_time;
  623. const inFeeRate = parseFloat(groupInfo[0].in_fee_rate) || 0;
  624. const inExchangeRate = parseFloat(groupInfo[0].in_exchange_rate) || 0;
  625. const outFeeRate = parseFloat(groupInfo[0].out_fee_rate) || 0;
  626. const outExchangeRate = parseFloat(groupInfo[0].out_exchange_rate) || 0;
  627. // 获取机器人加入后的交易记录
  628. const [records] = await pool.query(`
  629. SELECT t.*,
  630. COALESCE(t.fee_rate, g.in_fee_rate) as fee_rate,
  631. COALESCE(t.exchange_rate, g.in_exchange_rate) as exchange_rate
  632. FROM transactions t
  633. LEFT JOIN groups g ON t.group_id = g.group_id
  634. WHERE t.group_id = ?
  635. AND DATE(t.time) = CURDATE()
  636. ORDER BY t.time DESC
  637. `, [chatId.toString()]);
  638. if (!records || records.length === 0) {
  639. return '暂无交易记录';
  640. }
  641. const deposits = records.filter(r => r.type === 'deposit');
  642. const withdrawals = records.filter(r => r.type === 'withdrawal');
  643. const totalDeposit = deposits.reduce((sum, d) => sum + parseFloat(d.amount), 0);
  644. const totalWithdrawal = withdrawals.reduce((sum, w) => sum + parseFloat(w.amount), 0);
  645. const depositFee = totalDeposit * (inFeeRate / 100);
  646. const withdrawalFee = totalWithdrawal * (outFeeRate / 100);
  647. const remaining = totalDeposit - depositFee - totalWithdrawal - withdrawalFee;
  648. const remainingU = (remaining / inExchangeRate).toFixed(2);
  649. // 获取当前日期
  650. const today = new Date();
  651. const version = 'v29';
  652. const dateStr = today.toISOString().split('T')[0].replace(/-/g, '-');
  653. let message = `当前版本:<b>${dateStr}:${version}</b>\n\n`;
  654. // 添加入款记录
  655. if (deposits.length > 0) {
  656. message += `<b>入款笔数</b>:<code>${deposits.length}</code>\n`;
  657. deposits.forEach(deposit => {
  658. message += `<code>${moment(deposit.time).format('HH:mm:ss')} ${parseFloat(deposit.amount).toFixed(2)}</code>\n`;
  659. });
  660. message += '\n';
  661. } else {
  662. message += `<b>入款笔数</b>:<code>0</code>\n\n`;
  663. }
  664. // 添加出款记录
  665. if (withdrawals.length > 0) {
  666. message += `<b>出款笔数</b>:<code>${withdrawals.length}</code>\n`;
  667. withdrawals.forEach(withdrawal => {
  668. message += `<code>${moment(withdrawal.time).format('HH:mm:ss')} ${parseFloat(withdrawal.amount).toFixed(2)}</code>\n`;
  669. });
  670. message += '\n';
  671. } else {
  672. message += `<b>出款笔数</b>:<code>0</code>\n\n`;
  673. }
  674. // 添加费率信息
  675. message += `<b>入款费率</b>:<code>${inFeeRate}%</code>\n`;
  676. message += `<b>入款汇率</b>:<code>${inExchangeRate}</code>\n`;
  677. message += `<b>入款总额</b>:<code>${totalDeposit.toFixed(2)}</code>\n`;
  678. message += `<b>入款合计</b>:<code>${(totalDeposit - depositFee).toFixed(2)}|${((totalDeposit - depositFee) / inExchangeRate).toFixed(2)}U</code>\n\n`;
  679. message += `<b>出款费率</b>:<code>${outFeeRate}%</code>\n`;
  680. message += `<b>出款汇率</b>:<code>${outExchangeRate}</code>\n`;
  681. message += `<b>出款总额</b>:<code>${totalWithdrawal.toFixed(2)}</code>\n`;
  682. message += `<b>出款合计</b>:<code>${(totalWithdrawal - withdrawalFee).toFixed(2)}|${((totalWithdrawal - withdrawalFee) / outExchangeRate).toFixed(2)}U</code>\n\n`;
  683. // 添加余额信息
  684. message += `<b>应下发</b>:<code>${remainingU}U</code>\n`;
  685. message += `<b>已下发</b>:<code>${(totalWithdrawal / outExchangeRate).toFixed(2)}U</code>\n`;
  686. message += `<b>未下发</b>:<code>${(remainingU - (totalWithdrawal / outExchangeRate)).toFixed(2)}U</code>`;
  687. return message;
  688. } catch (error) {
  689. console.error(formatLog('生成账单消息失败', error));
  690. return '获取账单信息失败,请稍后重试';
  691. }
  692. }
  693. // 生成内联键盘
  694. function generateInlineKeyboard(chatId) {
  695. const keyboard = {
  696. inline_keyboard: [
  697. [{
  698. text: '点击跳转完整账单',
  699. callback_data: `bill_page_${chatId}`
  700. }],
  701. [{
  702. text: '24小时商务对接',
  703. callback_data: 'business_contact'
  704. }]
  705. ]
  706. };
  707. return keyboard;
  708. }
  709. // 处理内联按钮回调
  710. bot.on('callback_query', async (callbackQuery) => {
  711. const chatId = callbackQuery.message.chat.id;
  712. const data = callbackQuery.data;
  713. try {
  714. if (data.startsWith('bill_page_')) {
  715. const groupId = data.split('_')[2];
  716. await bot.answerCallbackQuery(callbackQuery.id, {
  717. url: 'https://google.com'
  718. });
  719. } else if (data === 'business_contact') {
  720. await bot.answerCallbackQuery(callbackQuery.id, {
  721. url: 'https://t.me/your_business_account'
  722. });
  723. }
  724. } catch (error) {
  725. console.error(formatLog('处理内联按钮回调失败', error));
  726. await bot.answerCallbackQuery(callbackQuery.id, {
  727. text: '操作失败,请稍后重试',
  728. show_alert: true
  729. });
  730. }
  731. });
  732. // 保存数据
  733. function saveData() {
  734. try {
  735. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  736. } catch (error) {
  737. console.error(formatLog('Error saving data', error));
  738. }
  739. }
  740. // 加载数据
  741. function loadData() {
  742. try {
  743. if (fs.existsSync(process.env.DB_FILE)) {
  744. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  745. data = {
  746. ...data,
  747. ...savedData
  748. };
  749. }
  750. } catch (error) {
  751. console.error(formatLog('Error loading data', error));
  752. }
  753. }
  754. // 测试数据库连接并初始化
  755. testConnection().then(() => {
  756. return initDatabase();
  757. }).then(() => {
  758. // 加载数据
  759. loadData();
  760. // 启动服务器
  761. const PORT = process.env.PORT || 3000;
  762. app.listen(PORT, () => {
  763. console.log(formatLog({
  764. PORT: PORT
  765. }));
  766. console.log('机器人已准备就绪!');
  767. });
  768. }).catch(error => {
  769. console.error(formatLog('启动失败', error));
  770. process.exit(1);
  771. });
  772. // 处理机器人被添加到群组
  773. async function handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup) {
  774. try {
  775. // 获取群组链接
  776. const chatInfo = await bot.getChat(chatId);
  777. const groupInfo = {
  778. ID: chatId,
  779. 名称: msg.chat.title || '未命名群组',
  780. 类型: chatType,
  781. 状态: existingGroup ? '重新激活' : '已激活',
  782. 群组链接: chatInfo.invite_link || '未设置',
  783. 更新时间: new Date().toLocaleString()
  784. };
  785. console.log(formatLog({
  786. 操作: '处理机器人添加',
  787. 群组信息: groupInfo
  788. }));
  789. // 如果群组不存在,创建新群组
  790. if (!existingGroup) {
  791. const groupData = {
  792. groupId: chatIdStr,
  793. groupName: msg.chat.title || '未命名群组',
  794. groupType: chatType === 'private' ? 'personal' : chatType,
  795. creatorId: msg.from.id.toString()
  796. };
  797. try {
  798. // 检查群组是否已经存在
  799. const [existingGroupCheck] = await pool.query(
  800. 'SELECT * FROM groups WHERE group_id = ?',
  801. [chatIdStr]
  802. );
  803. if (existingGroupCheck && existingGroupCheck.length > 0) {
  804. console.log(formatLog({
  805. 操作: '群组已存在,更新状态',
  806. 群组ID: chatIdStr
  807. }));
  808. // 更新现有群组状态
  809. await pool.query(`
  810. UPDATE groups
  811. SET is_active = true,
  812. group_name = ?,
  813. group_type = ?,
  814. last_join_time = CURRENT_TIMESTAMP
  815. WHERE group_id = ?
  816. `, [
  817. groupData.groupName,
  818. groupData.groupType,
  819. chatIdStr
  820. ]);
  821. } else {
  822. // 创建新群组
  823. await pool.query(`
  824. INSERT INTO groups
  825. (group_id, group_name, group_type, creator_id, is_active, last_join_time,
  826. in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate, operators)
  827. VALUES (?, ?, ?, ?, true, CURRENT_TIMESTAMP, 0.00, 1.0000, 0.00, 1.0000, '[]')
  828. `, [
  829. groupData.groupId,
  830. groupData.groupName,
  831. groupData.groupType,
  832. groupData.creatorId
  833. ]);
  834. }
  835. // 更新内存中的群组列表
  836. if (!data.allowedGroups.includes(chatIdStr)) {
  837. data.allowedGroups.push(chatIdStr);
  838. saveData();
  839. }
  840. // 发送欢迎消息
  841. await bot.sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。', {
  842. parse_mode: 'HTML'
  843. });
  844. // 发送账单消息
  845. const billMessage = await generateBillMessage(chatId);
  846. if (billMessage) {
  847. await bot.sendMessage(chatId, billMessage, {
  848. parse_mode: 'HTML',
  849. reply_markup: generateInlineKeyboard(chatId)
  850. });
  851. }
  852. console.log(formatLog({
  853. 操作: '群组添加成功',
  854. 群组ID: chatIdStr,
  855. 群组名称: groupData.groupName
  856. }));
  857. } catch (error) {
  858. console.error(formatLog({
  859. 错误: '创建群组失败',
  860. 详情: error.message,
  861. 群组ID: groupData.groupId
  862. }));
  863. // 检查是否是重复添加导致的错误
  864. if (error.code === 'ER_DUP_ENTRY') {
  865. console.log(formatLog({
  866. 操作: '检测到重复添加',
  867. 群组ID: chatIdStr
  868. }));
  869. return;
  870. }
  871. await bot.sendMessage(chatId, '添加群组失败,请联系管理员。', {
  872. parse_mode: 'HTML'
  873. });
  874. }
  875. }
  876. } catch (error) {
  877. console.error(formatLog({
  878. 错误: '处理群组添加失败',
  879. 详情: error.message
  880. }));
  881. await sendMessage(chatId, '添加群组失败,请联系管理员。');
  882. }
  883. }
  884. // 处理群组信息更新
  885. async function handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus, newType) {
  886. const connection = await pool.getConnection();
  887. await connection.beginTransaction();
  888. try {
  889. // 更新群组ID和类型
  890. const oldGroupId = existingGroup.group_id;
  891. // 如果群组ID发生变化,更新所有相关记录
  892. if (existingGroup.group_type != newType) {
  893. console.log(formatLog({
  894. 操作: '群组类型更新',
  895. 名称: msg.chat.title || existingGroup.group_name,
  896. 旧ID: oldGroupId,
  897. 新ID: chatIdStr,
  898. 旧类型: existingGroup.group_type,
  899. 新类型: newType,
  900. 状态: newStatus !== 'kicked' && newStatus !== 'left' ? '活跃' : '已移除'
  901. }));
  902. // 开始事务
  903. await connection.beginTransaction();
  904. try {
  905. // 检查目标ID是否已存在
  906. const [existingTargetGroup] = await connection.query(
  907. 'SELECT * FROM groups WHERE group_id = ?',
  908. [chatIdStr]
  909. );
  910. if (existingTargetGroup && existingTargetGroup.length > 0) {
  911. // 更新交易记录
  912. await connection.query(`
  913. UPDATE transactions
  914. SET group_id = ?
  915. WHERE group_id = ?
  916. `, [chatIdStr, oldGroupId]);
  917. // 更新资金记录
  918. await connection.query(`
  919. UPDATE money_records
  920. SET group_id = ?
  921. WHERE group_id = ?
  922. `, [chatIdStr, oldGroupId]);
  923. // 删除旧群组记录
  924. await connection.query(
  925. 'DELETE FROM groups WHERE group_id = ?',
  926. [oldGroupId]
  927. );
  928. // 更新目标群组信息
  929. await connection.query(`
  930. UPDATE groups
  931. SET group_type = ?,
  932. group_name = ?,
  933. is_active = ?,
  934. updated_at = CURRENT_TIMESTAMP
  935. WHERE group_id = ?
  936. `, [
  937. newType,
  938. msg.chat.title || existingGroup.group_name,
  939. newStatus !== 'kicked' && newStatus !== 'left',
  940. chatIdStr
  941. ]);
  942. } else {
  943. // 如果目标ID不存在,执行正常的更新操作
  944. // 先删除旧记录
  945. await connection.query(
  946. 'DELETE FROM groups WHERE group_id = ?',
  947. [oldGroupId]
  948. );
  949. // 插入新记录
  950. await connection.query(`
  951. INSERT INTO groups
  952. (group_id, group_name, group_type, creator_id, is_active, last_join_time)
  953. VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
  954. `, [
  955. chatIdStr,
  956. msg.chat.title || existingGroup.group_name,
  957. newType,
  958. existingGroup.creator_id,
  959. newStatus !== 'kicked' && newStatus !== 'left'
  960. ]);
  961. // 更新交易记录
  962. await connection.query(`
  963. UPDATE transactions
  964. SET group_id = ?
  965. WHERE group_id = ?
  966. `, [chatIdStr, oldGroupId]);
  967. // 更新资金记录
  968. await connection.query(`
  969. UPDATE money_records
  970. SET group_id = ?
  971. WHERE group_id = ?
  972. `, [chatIdStr, oldGroupId]);
  973. }
  974. // 提交事务
  975. await connection.commit();
  976. // 更新内存中的群组列表
  977. const index = data.allowedGroups.indexOf(oldGroupId);
  978. if (index > -1) {
  979. if (newStatus === 'kicked' || newStatus === 'left') {
  980. data.allowedGroups.splice(index, 1);
  981. } else {
  982. data.allowedGroups[index] = chatIdStr;
  983. }
  984. saveData();
  985. }
  986. } catch (error) {
  987. // 回滚事务
  988. await connection.rollback();
  989. console.error(formatLog('更新群组信息失败', error));
  990. throw error;
  991. }
  992. } else {
  993. // 如果ID没有变化,只更新其他信息
  994. await connection.query(`
  995. UPDATE groups
  996. SET group_type = ?,
  997. group_name = ?,
  998. is_active = ?,
  999. updated_at = CURRENT_TIMESTAMP
  1000. WHERE group_id = ?
  1001. `, [
  1002. newType,
  1003. msg.chat.title || existingGroup.group_name,
  1004. newStatus !== 'kicked' && newStatus !== 'left',
  1005. chatIdStr
  1006. ]);
  1007. }
  1008. await connection.commit();
  1009. console.log('【群组状态变更】');
  1010. console.log(formatLog({
  1011. ID: oldGroupId + ' -> ' + chatIdStr,
  1012. type: existingGroup.group_type + ' -> ' + newType,
  1013. name: existingGroup.group_name + ' -> ' + msg.chat.title || existingGroup.group_name,
  1014. status: newStatus === 'kicked' || newStatus === 'left' ? '已移除' : '活跃'
  1015. }));
  1016. } catch (error) {
  1017. await connection.rollback();
  1018. console.error(formatLog({
  1019. 错误: '更新群组信息失败',
  1020. 详情: error.message
  1021. }));
  1022. throw error;
  1023. } finally {
  1024. connection.release();
  1025. }
  1026. }
  1027. // 处理群组状态变更
  1028. bot.on('my_chat_member', async (msg) => {
  1029. try {
  1030. const chatId = msg.chat.id;
  1031. const newStatus = msg.new_chat_member.status;
  1032. const oldStatus = msg.old_chat_member.status;
  1033. const chatType = msg.chat.type;
  1034. const chatIdStr = chatId.toString();
  1035. console.log(formatLog({
  1036. 操作: '收到群组状态变更',
  1037. 群组ID: chatIdStr,
  1038. 群组名称: msg.chat.title,
  1039. 旧状态: oldStatus,
  1040. 新状态: newStatus,
  1041. 群组类型: chatType
  1042. }));
  1043. // 定义群组类型
  1044. const newType = chatType === 'private' ? 'personal' :
  1045. chatType === 'supergroup' ? 'supergroup' : 'group';
  1046. // 查找群组,同时检查新旧ID
  1047. const existingGroup = await Group.findByGroupId(chatIdStr) ||
  1048. await Group.findByGroupId(chatIdStr.replace('-', ''));
  1049. // 如果是机器人首次被添加到群组(从非成员变为成员)
  1050. if (oldStatus === 'left' && newStatus === 'member') {
  1051. // 如果群组已存在且处于活跃状态,则发送欢迎消息
  1052. if (existingGroup && existingGroup.is_active) {
  1053. console.log(formatLog({
  1054. 操作: '机器人重新加入群组',
  1055. 群组ID: chatIdStr,
  1056. 群组名称: msg.chat.title || existingGroup.group_name
  1057. }));
  1058. try {
  1059. // 发送欢迎消息
  1060. await bot.sendMessage(chatId, '感谢重新添加我为群组成员!', {
  1061. parse_mode: 'HTML'
  1062. });
  1063. // 发送账单消息
  1064. const billMessage = await generateBillMessage(chatId);
  1065. if (billMessage) {
  1066. await bot.sendMessage(chatId, billMessage, {
  1067. parse_mode: 'HTML',
  1068. reply_markup: generateInlineKeyboard(chatId)
  1069. });
  1070. }
  1071. } catch (error) {
  1072. console.error(formatLog({
  1073. 错误: '发送消息失败',
  1074. 详情: error.message,
  1075. 群组ID: chatIdStr
  1076. }));
  1077. }
  1078. return;
  1079. }
  1080. // 检查邀请者是否已存在于用户表中
  1081. const [existingUser] = await pool.query(
  1082. 'SELECT * FROM users WHERE id = ?',
  1083. [msg.from.id]
  1084. );
  1085. // 如果用户不存在,则创建新用户
  1086. if (!existingUser || existingUser.length === 0) {
  1087. // 生成唯一的用户名
  1088. const username = msg.from.username || `user_${msg.from.id}`;
  1089. await pool.query(`
  1090. INSERT INTO users
  1091. (id, username, password, role)
  1092. VALUES (?, ?, '', 'user')
  1093. `, [msg.from.id, username]);
  1094. console.log(formatLog({
  1095. 操作: '新增用户',
  1096. ID: msg.from.id,
  1097. 用户名: username,
  1098. 角色: 'user',
  1099. 时间: new Date().toLocaleString()
  1100. }));
  1101. }
  1102. if (!existingGroup) {
  1103. await handleBotAdded(msg, chatId, chatType, chatIdStr, null);
  1104. } else if (existingGroup.group_type !== newType) {
  1105. await handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup);
  1106. }
  1107. }
  1108. if (existingGroup) {
  1109. // 传递 newType 到 handleGroupUpdate 函数
  1110. await handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus, newType);
  1111. } else if (newStatus === 'member') {
  1112. // 如果是新群组且机器人被添加为成员
  1113. await handleBotAdded(msg, chatId, chatType, chatIdStr, null);
  1114. }
  1115. } catch (error) {
  1116. console.error(formatLog({
  1117. 错误: '处理群组状态变更失败',
  1118. 详情: error.message
  1119. }));
  1120. }
  1121. });
  1122. // 导入公共路由
  1123. const publicRoutes = require('./routes/public');
  1124. // 注册公共路由
  1125. app.use('/api/public', publicRoutes);
  1126. // 错误处理中间件
  1127. app.use((err, req, res, next) => {
  1128. console.error(err.stack);
  1129. res.status(500).json({ message: '服务器错误' });
  1130. });
  1131. // 404 处理
  1132. app.use((req, res) => {
  1133. res.status(404).json({ message: '未找到请求的资源' });
  1134. });
  1135. module.exports = app;