index.js 45 KB

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