index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 { pool, testConnection } = require('./config/database');
  9. const initDatabase = require('./config/initDb');
  10. const Group = require('./models/Group');
  11. const Transaction = require('./models/Transaction');
  12. const app = express();
  13. // 初始化数据存储
  14. let data = {
  15. deposits: [], // 入款记录
  16. withdrawals: [], // 下发记录
  17. lastUpdate: null,
  18. allowedGroups: ['4754375683'] // 允许使用的群组ID
  19. };
  20. // 创建机器人实例
  21. const bot = new TelegramBot(process.env.BOT_TOKEN, { polling: true });
  22. // 中间件
  23. app.use(cors());
  24. app.use(express.json());
  25. app.use(express.static('views'));
  26. // 路由
  27. app.get('/', (req, res) => {
  28. res.sendFile(path.join(__dirname, 'views', 'login.html'));
  29. });
  30. app.use('/api/users', require('./routes/userRoutes'));
  31. app.use('/api/groups', require('./routes/groupRoutes'));
  32. app.use('/api/transactions', require('./routes/transactionRoutes'));
  33. // 检查群组权限
  34. function isGroupAllowed(chatId) {
  35. const chatIdStr = chatId.toString();
  36. return data.allowedGroups.includes(chatIdStr) ||
  37. data.allowedGroups.includes(chatIdStr.replace('-', ''));
  38. }
  39. // 检查是否是管理员
  40. function isAdmin(userId) {
  41. return process.env.ADMIN_IDS.split(',').includes(userId.toString());
  42. }
  43. // 处理消息发送
  44. async function sendMessage(chatId, text, options = {}) {
  45. try {
  46. // 如果包含内联键盘,验证URL
  47. if (options.reply_markup && options.reply_markup.inline_keyboard) {
  48. const keyboard = generateInlineKeyboard(chatId);
  49. if (!keyboard) {
  50. // 如果键盘无效,发送不带键盘的消息
  51. return await bot.sendMessage(chatId, text);
  52. }
  53. options.reply_markup = keyboard;
  54. }
  55. return await bot.sendMessage(chatId, text, options);
  56. } catch (error) {
  57. console.error('发送消息失败:', error);
  58. if (error.message.includes('bot was kicked from the group chat')) {
  59. const index = data.allowedGroups.indexOf(chatId.toString());
  60. if (index > -1) {
  61. data.allowedGroups.splice(index, 1);
  62. saveData();
  63. console.log(`群组 ${chatId} 已被移除出允许列表`);
  64. }
  65. }
  66. return null;
  67. }
  68. }
  69. // 处理快捷命令
  70. bot.on('message', async (msg) => {
  71. if (!isGroupAllowed(msg.chat.id)) return;
  72. const text = msg.text?.trim();
  73. if (!text) return;
  74. if (text.startsWith('+')) {
  75. const amount = parseFloat(text.substring(1));
  76. if (!isNaN(amount)) {
  77. const transactionData = {
  78. groupId: msg.chat.id.toString(),
  79. groupName: msg.chat.title || '未命名群组',
  80. amount: amount
  81. };
  82. try {
  83. const result = await Transaction.deposit(transactionData);
  84. if (result.success) {
  85. const billMessage = await generateBillMessage(msg.chat.id);
  86. if (billMessage) {
  87. await sendMessage(msg.chat.id, billMessage, {
  88. reply_markup: generateInlineKeyboard(msg.chat.id)
  89. });
  90. console.log(`入款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  91. } else {
  92. await sendMessage(msg.chat.id, '入款成功,但获取账单信息失败');
  93. console.log(`入款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  94. }
  95. } else {
  96. await sendMessage(msg.chat.id, result.message || '入款失败');
  97. console.log(`入款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  98. }
  99. } catch (error) {
  100. console.error('快捷入款失败:', error);
  101. await sendMessage(msg.chat.id, '记录入款失败,请稍后重试');
  102. }
  103. }
  104. } else if (text.startsWith('-')) {
  105. const amount = parseFloat(text.substring(1));
  106. if (!isNaN(amount)) {
  107. const transactionData = {
  108. groupId: msg.chat.id.toString(),
  109. groupName: msg.chat.title || '未命名群组',
  110. amount: amount
  111. };
  112. try {
  113. const result = await Transaction.withdrawal(transactionData);
  114. if (result.success) {
  115. const billMessage = await generateBillMessage(msg.chat.id);
  116. if (billMessage) {
  117. await sendMessage(msg.chat.id, billMessage, {
  118. reply_markup: generateInlineKeyboard(msg.chat.id)
  119. });
  120. console.log(`出款成功 - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  121. } else {
  122. await sendMessage(msg.chat.id, '出款成功,但获取账单信息失败');
  123. console.log(`出款成功(无账单) - 群组: ${msg.chat.title}, 金额: ${amount}, 时间: ${new Date().toLocaleString()}`);
  124. }
  125. } else {
  126. await sendMessage(msg.chat.id, result.message || '出款失败');
  127. console.log(`出款失败 - 群组: ${msg.chat.title}, 金额: ${amount}, 原因: ${result.message}, 时间: ${new Date().toLocaleString()}`);
  128. }
  129. } catch (error) {
  130. console.error('快捷出款失败:', error);
  131. await sendMessage(msg.chat.id, '记录出款失败,请稍后重试');
  132. }
  133. }
  134. }
  135. });
  136. // 处理新成员加入
  137. bot.on('new_chat_members', async (msg) => {
  138. const chatId = msg.chat.id;
  139. const newMembers = msg.new_chat_members;
  140. for (const member of newMembers) {
  141. if (member.id === (await bot.getMe()).id) {
  142. // 机器人被添加到群组
  143. console.log(`机器人被添加到群组: ${chatId}`);
  144. // 检查群组是否在允许列表中
  145. const chatIdStr = chatId.toString();
  146. if (!data.allowedGroups.includes(chatIdStr)) {
  147. try {
  148. const groupData = {
  149. groupId: chatIdStr,
  150. groupName: msg.chat.title || '未命名群组',
  151. groupType: msg.chat.type === 'private' ? 'personal' : 'public',
  152. creatorId: msg.from.id.toString()
  153. };
  154. const id = await Group.create({
  155. groupId: groupData.groupId,
  156. groupName: groupData.groupName,
  157. creatorId: groupData.creatorId
  158. });
  159. const group = await Group.findById(id);
  160. if (group) {
  161. // 更新内存中的群组列表
  162. data.allowedGroups.push(chatIdStr);
  163. saveData();
  164. sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。');
  165. } else {
  166. sendMessage(chatId, '添加群组失败,请联系管理员。');
  167. }
  168. } catch (error) {
  169. console.error('创建群组失败:', error);
  170. sendMessage(chatId, '添加群组失败,请联系管理员。');
  171. }
  172. } else {
  173. sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。');
  174. }
  175. } else {
  176. // 其他新成员
  177. console.log(`新成员加入群组: ${member.username || member.first_name} (${member.id})`);
  178. sendMessage(chatId, `欢迎 ${member.username || member.first_name} 加入群组!`);
  179. }
  180. }
  181. });
  182. // 处理管理员命令
  183. bot.onText(/\/addgroup (.+)/, async (msg, match) => {
  184. if (!isAdmin(msg.from.id)) {
  185. sendMessage(msg.chat.id, '您没有权限执行此命令。');
  186. return;
  187. }
  188. const groupId = match[1].trim();
  189. if (!data.allowedGroups.includes(groupId)) {
  190. try {
  191. // 使用 createGroup 创建新群组
  192. const groupData = {
  193. groupId: groupId,
  194. groupName: '手动添加的群组',
  195. groupType: 'public',
  196. creatorId: msg.from.id.toString()
  197. };
  198. const result = await createGroup({ body: groupData });
  199. if (result) {
  200. data.allowedGroups.push(groupId);
  201. saveData();
  202. sendMessage(msg.chat.id, `群组 ${groupId} 已添加到允许列表。`);
  203. } else {
  204. sendMessage(msg.chat.id, '添加群组失败,请检查群组ID是否正确。');
  205. }
  206. } catch (error) {
  207. console.error('创建群组失败:', error);
  208. sendMessage(msg.chat.id, '添加群组失败,请稍后重试。');
  209. }
  210. } else {
  211. sendMessage(msg.chat.id, '该群组已在允许列表中。');
  212. }
  213. });
  214. bot.onText(/\/removegroup (.+)/, async (msg, match) => {
  215. if (!isAdmin(msg.from.id)) {
  216. sendMessage(msg.chat.id, '您没有权限执行此命令。');
  217. return;
  218. }
  219. const groupId = match[1].trim();
  220. try {
  221. // 使用 updateGroup 更新群组状态
  222. const result = await updateGroup({
  223. params: { id: groupId },
  224. body: { isActive: false }
  225. });
  226. if (result) {
  227. const index = data.allowedGroups.indexOf(groupId);
  228. if (index > -1) {
  229. data.allowedGroups.splice(index, 1);
  230. saveData();
  231. sendMessage(msg.chat.id, `群组 ${groupId} 已从允许列表中移除。`);
  232. } else {
  233. sendMessage(msg.chat.id, '该群组不在允许列表中。');
  234. }
  235. } else {
  236. sendMessage(msg.chat.id, '移除群组失败,请稍后重试。');
  237. }
  238. } catch (error) {
  239. console.error('更新群组状态失败:', error);
  240. sendMessage(msg.chat.id, '移除群组失败,请稍后重试。');
  241. }
  242. });
  243. bot.onText(/\/listgroups/, async (msg) => {
  244. if (!isAdmin(msg.from.id)) {
  245. sendMessage(msg.chat.id, '您没有权限执行此命令。');
  246. return;
  247. }
  248. try {
  249. const groups = await pool.query('SELECT group_id, group_name, group_type, is_active FROM groups WHERE is_active = 1');
  250. if (groups.length === 0) {
  251. sendMessage(msg.chat.id, '当前没有允许的群组。');
  252. return;
  253. }
  254. const groupsList = groups.map(group =>
  255. `ID: ${group.group_id}\n名称: ${group.group_name}\n类型: ${group.group_type}\n状态: ${group.is_active ? '启用' : '禁用'}`
  256. ).join('\n\n');
  257. sendMessage(msg.chat.id, `允许的群组列表:\n\n${groupsList}`);
  258. } catch (error) {
  259. console.error('获取群组列表失败:', error);
  260. sendMessage(msg.chat.id, '获取群组列表失败,请稍后重试。');
  261. }
  262. });
  263. // 处理入款命令
  264. bot.onText(/\/deposit (.+)/, async (msg, match) => {
  265. if (!isGroupAllowed(msg.chat.id)) {
  266. sendMessage(msg.chat.id, '该群组未授权使用此功能');
  267. return;
  268. }
  269. const amount = parseFloat(match[1]);
  270. if (isNaN(amount)) {
  271. sendMessage(msg.chat.id, '请输入有效的金额');
  272. return;
  273. }
  274. try {
  275. const transactionData = {
  276. groupId: msg.chat.id.toString(),
  277. groupName: msg.chat.title || '未命名群组',
  278. amount: amount
  279. };
  280. const result = await Transaction.deposit(transactionData);
  281. if (result.success) {
  282. sendMessage(msg.chat.id, generateBillMessage(msg.chat.id), {
  283. reply_markup: generateInlineKeyboard(msg.chat.id)
  284. });
  285. console.log('机器人已准备就绪!');
  286. } else {
  287. sendMessage(msg.chat.id, result.message);
  288. console.log('机器人已准备就绪!');
  289. }
  290. } catch (error) {
  291. console.error('记录入款失败:', error);
  292. sendMessage(msg.chat.id, '记录入款失败,请稍后重试');
  293. }
  294. });
  295. // 处理下发命令
  296. bot.onText(/\/withdraw (.+)/, async (msg, match) => {
  297. if (!isGroupAllowed(msg.chat.id)) {
  298. sendMessage(msg.chat.id, '该群组未授权使用此功能');
  299. return;
  300. }
  301. const amount = parseFloat(match[1]);
  302. if (isNaN(amount)) {
  303. sendMessage(msg.chat.id, '请输入有效的金额');
  304. return;
  305. }
  306. try {
  307. const transactionData = {
  308. groupId: msg.chat.id.toString(),
  309. groupName: msg.chat.title || '未命名群组',
  310. amount: amount
  311. };
  312. const result = await Transaction.withdrawal(transactionData);
  313. if (result.success) {
  314. sendMessage(msg.chat.id, generateBillMessage(msg.chat.id), {
  315. reply_markup: generateInlineKeyboard(msg.chat.id)
  316. });
  317. } else {
  318. sendMessage(msg.chat.id, result.message);
  319. }
  320. } catch (error) {
  321. console.error('记录下发失败:', error);
  322. sendMessage(msg.chat.id, '记录下发失败,请稍后重试');
  323. }
  324. });
  325. // 处理查看账单命令
  326. bot.onText(/\/bill/, async (msg) => {
  327. const billMessage = await generateBillMessage(msg.chat.id);
  328. sendMessage(msg.chat.id, billMessage, {
  329. reply_markup: generateInlineKeyboard(msg.chat.id)
  330. });
  331. });
  332. // 更新帮助命令
  333. bot.onText(/\/help/, (msg) => {
  334. const helpMessage = `
  335. 可用命令:
  336. /deposit <金额> - 记录入款
  337. /withdraw <金额> - 记录下发
  338. /bill - 查看当前账单
  339. /help - 显示此帮助信息
  340. 快捷命令:
  341. +<金额> - 快速记录入款(例如:+2000)
  342. -<金额> - 快速记录下发(例如:-2000)
  343. 管理员命令:
  344. /addgroup <群组ID> - 添加允许的群组
  345. /removegroup <群组ID> - 移除允许的群组
  346. /listgroups - 列出所有允许的群组
  347. `;
  348. sendMessage(msg.chat.id, helpMessage);
  349. });
  350. // 生成账单消息
  351. async function generateBillMessage(chatId) {
  352. try {
  353. // 获取最近的交易记录
  354. const [records] = await pool.query(`
  355. SELECT * FROM transactions
  356. WHERE group_id = ?
  357. ORDER BY time DESC
  358. LIMIT 10
  359. `, [chatId.toString()]);
  360. if (!records || records.length === 0) {
  361. return '暂无交易记录';
  362. }
  363. const deposits = records.filter(r => r.type === 'deposit');
  364. const withdrawals = records.filter(r => r.type === 'withdrawal');
  365. const totalDeposit = deposits.reduce((sum, d) => sum + parseFloat(d.amount), 0);
  366. const totalWithdrawal = withdrawals.reduce((sum, w) => sum + parseFloat(w.amount), 0);
  367. const depositFee = totalDeposit * (process.env.DEPOSIT_FEE_RATE || 0);
  368. const withdrawalFee = totalWithdrawal * (process.env.WITHDRAWAL_FEE_RATE || 0);
  369. const remaining = totalDeposit - depositFee - totalWithdrawal - withdrawalFee;
  370. let message = `入款(${deposits.length})笔:\n`;
  371. // 添加入款记录
  372. deposits.forEach(deposit => {
  373. message += `${moment(deposit.time).format('HH:mm:ss')} ${parseFloat(deposit.amount).toFixed(2)}\n`;
  374. });
  375. message += `\n下发(${withdrawals.length})笔:\n`;
  376. // 添加下发记录
  377. withdrawals.forEach(withdrawal => {
  378. message += `${moment(withdrawal.time).format('HH:mm:ss')} ${parseFloat(withdrawal.amount).toFixed(2)}\n`;
  379. });
  380. message += `\n总入款:${totalDeposit.toFixed(2)}\n`;
  381. message += `入款费率:${((process.env.DEPOSIT_FEE_RATE || 0) * 100).toFixed(1)}%\n`;
  382. message += `下发费率:${((process.env.WITHDRAWAL_FEE_RATE || 0) * 100).toFixed(1)}%\n`;
  383. message += `应下发:${(totalDeposit - depositFee).toFixed(2)}\n`;
  384. message += `总下发:${totalWithdrawal.toFixed(2)}\n`;
  385. message += `下发单笔附加费:0.0\n`;
  386. message += `单笔附费加总计:0.0\n`;
  387. message += `余:${remaining.toFixed(2)}`;
  388. return message;
  389. } catch (error) {
  390. console.error('生成账单消息失败:', error);
  391. return '获取账单信息失败,请稍后重试';
  392. }
  393. }
  394. // 生成内联键盘
  395. function generateInlineKeyboard(chatId) {
  396. const keyboard = {
  397. inline_keyboard: [
  398. [
  399. {
  400. text: '点击跳转完整账单',
  401. callback_data: `bill_page_${chatId}`
  402. }
  403. ],
  404. [
  405. {
  406. text: '24小时商务对接',
  407. callback_data: 'business_contact'
  408. }
  409. ]
  410. ]
  411. };
  412. return keyboard;
  413. }
  414. // 处理内联按钮回调
  415. bot.on('callback_query', async (callbackQuery) => {
  416. const chatId = callbackQuery.message.chat.id;
  417. const data = callbackQuery.data;
  418. try {
  419. if (data.startsWith('bill_page_')) {
  420. const groupId = data.split('_')[2];
  421. await bot.answerCallbackQuery(callbackQuery.id, {
  422. url: `${process.env.BILL_PAGE_BASE_URL}?groupId=${groupId}`
  423. });
  424. } else if (data === 'business_contact') {
  425. await bot.answerCallbackQuery(callbackQuery.id, {
  426. url: 'https://t.me/your_business_account'
  427. });
  428. }
  429. } catch (error) {
  430. console.error('处理内联按钮回调失败:', error);
  431. await bot.answerCallbackQuery(callbackQuery.id, {
  432. text: '操作失败,请稍后重试',
  433. show_alert: true
  434. });
  435. }
  436. });
  437. // 保存数据
  438. function saveData() {
  439. try {
  440. fs.writeFileSync(process.env.DB_FILE, JSON.stringify(data, null, 2));
  441. } catch (error) {
  442. console.error('Error saving data:', error);
  443. }
  444. }
  445. // 加载数据
  446. function loadData() {
  447. try {
  448. if (fs.existsSync(process.env.DB_FILE)) {
  449. const savedData = JSON.parse(fs.readFileSync(process.env.DB_FILE));
  450. data = { ...data, ...savedData };
  451. }
  452. } catch (error) {
  453. console.error('Error loading data:', error);
  454. }
  455. }
  456. // 测试数据库连接并初始化
  457. testConnection().then(() => {
  458. return initDatabase();
  459. }).then(() => {
  460. // 加载数据
  461. loadData();
  462. // 启动服务器
  463. const PORT = process.env.PORT || 3000;
  464. app.listen(PORT, () => {
  465. console.log(`服务器运行在端口 ${PORT}`);
  466. console.log('机器人已准备就绪!');
  467. });
  468. }).catch(error => {
  469. console.error('启动失败:', error);
  470. process.exit(1);
  471. });