Kaynağa Gözat

操作人权限检查

Taio_O 3 hafta önce
ebeveyn
işleme
a3af553273
2 değiştirilmiş dosya ile 156 ekleme ve 241 silme
  1. 156 240
      admin/index.js
  2. 0 1
      admin/数据文件路径

+ 156 - 240
admin/index.js

@@ -572,185 +572,6 @@ bot.on('message', async (msg) => {
     }
 });
 
-// 处理新成员加入
-bot.on('new_chat_members', async (msg) => {
-    const chatId = msg.chat.id;
-    const newMembers = msg.new_chat_members;
-
-    for (const member of newMembers) {
-        if (member.id === (await bot.getMe()).id) {
-            // 检查群组是否在允许列表中
-            const chatIdStr = chatId.toString();
-            try {
-                // 先检查数据库中是否存在该群组
-                const existingGroup = await Group.findByGroupId(chatIdStr);
-
-                // 检查邀请者是否已存在于用户表中
-                const [existingUser] = await pool.query(
-                    'SELECT * FROM users WHERE id = ?',
-                    [msg.from.id]
-                );
-
-                // 如果用户不存在,则创建新用户
-                if (!existingUser || existingUser.length === 0) {
-                    // 生成唯一的用户名
-                    const username = msg.from.username || `user_${msg.from.id}`;
-                    
-                    await pool.query(`
-                        INSERT INTO users 
-                        (id, username, password, role) 
-                        VALUES (?, ?, '', 'user')
-                    `, [msg.from.id, username]);
-
-                    console.log(formatLog({
-                        操作: '新增用户',
-                        ID: msg.from.id,
-                        用户名: username,
-                        角色: 'user',
-                        时间: new Date().toLocaleString()
-                    }));
-                }
-
-                if (existingGroup) {
-                    // 如果群组存在,更新群组状态为活跃,同时更新群组名称和加入时间
-                    await pool.query(`
-                        UPDATE groups 
-                        SET is_active = true,
-                            group_name = ?,
-                            last_join_time = CURRENT_TIMESTAMP
-                        WHERE group_id = ?
-                    `, [msg.chat.title || existingGroup.group_name, chatIdStr]);
-
-                    // 更新内存中的群组列表
-                    if (!data.allowedGroups.includes(chatIdStr)) {
-                        data.allowedGroups.push(chatIdStr);
-                        saveData();
-                    }
-
-                    // 发送欢迎消息并显示当前账单
-                    await sendMessage(chatId, '感谢重新添加我为群组成员!');
-                    const billMessage = await generateBillMessage(chatId);
-                    if (billMessage) {
-                        await sendMessage(chatId, billMessage, {
-                            reply_markup: generateInlineKeyboard(chatId)
-                        });
-                    }
-                } else {
-                    // 如果是新群组,打印被添加到新群组的信息
-                    console.log(formatLog({
-                        ID: chatId,
-                        名称: msg.chat.title || '未命名群组',
-                        类型: msg.chat.type,
-                        描述: msg.chat.description || '无',
-                        '添加者信息': {
-                            ID: msg.from.id,
-                            用户名: msg.from.username || '无',
-                            姓名: msg.from.first_name,
-                            ...(msg.from.last_name && {
-                                姓: msg.from.last_name
-                            })
-                        },
-                        添加时间: new Date().toLocaleString()
-                    }));
-
-                    // 如果群组不存在,创建新群组
-                    const groupData = {
-                        groupId: chatIdStr,
-                        groupName: msg.chat.title || '未命名群组',
-                        groupType: msg.chat.type === 'private' ? 'personal' : msg.chat.type,
-                        creatorId: msg.from.id.toString()
-                    };
-
-                    console.log(formatLog(groupData));
-
-                    try {
-                        // 直接使用 SQL 插入或更新群组数据
-                        const [result] = await pool.query(`
-                            INSERT INTO groups 
-                            (group_id, group_name, group_type, creator_id, is_active, last_join_time, 
-                             in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate, operators) 
-                            VALUES (?, ?, ?, ?, true, CURRENT_TIMESTAMP, 0.00, 1.0000, 0.00, 1.0000, '[]')
-                            ON DUPLICATE KEY UPDATE
-                            group_name = VALUES(group_name),
-                            group_type = VALUES(group_type),
-                            is_active = true,
-                            last_join_time = CURRENT_TIMESTAMP
-                        `, [
-                            groupData.groupId,
-                            groupData.groupName,
-                            groupData.groupType,
-                            groupData.creatorId
-                        ]);
-
-                        console.log(formatLog(result));
-
-                        // 更新内存中的群组列表
-                        if (!data.allowedGroups.includes(chatIdStr)) {
-                            data.allowedGroups.push(chatIdStr);
-                            saveData();
-                            console.log(formatLog({
-                                ID: chatIdStr,
-                                名称: groupData.groupName,
-                                类型: groupData.groupType,
-                                状态: '已启用',
-                                添加时间: new Date().toLocaleString(),
-                                操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
-                            }));
-                        }
-
-                        console.log(formatLog({
-                            ID: chatIdStr,
-                            名称: groupData.groupName,
-                            类型: groupData.groupType,
-                            状态: '已启用',
-                            添加时间: new Date().toLocaleString(),
-                            操作者: msg.from.username || msg.from.first_name + ' (' + msg.from.id + ')'
-                        }));
-
-                        try {
-                            // 尝试发送欢迎消息
-                            const welcomeMessage = await bot.sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。', {
-                                parse_mode: 'HTML'
-                            });
-                            console.log(formatLog(welcomeMessage));
-
-                            // 尝试发送账单消息
-                            const billMessage = await generateBillMessage(chatId);
-                            if (billMessage) {
-                                const billResult = await bot.sendMessage(chatId, billMessage, {
-                                    parse_mode: 'HTML',
-                                    reply_markup: generateInlineKeyboard(chatId)
-                                });
-                                console.log(formatLog(billResult));
-                            }
-                        } catch (messageError) {
-                            console.error(formatLog(messageError));
-                        }
-                    } catch (error) {
-                        console.error(formatLog('创建群组过程中出错', error));
-                        try {
-                            await bot.sendMessage(chatId, '添加群组失败,请联系管理员。', {
-                                parse_mode: 'HTML'
-                            });
-                        } catch (messageError) {
-                            console.error(formatLog('发送错误消息失败', messageError));
-                        }
-                    }
-                }
-            } catch (error) {
-                console.error(formatLog('处理群组加入失败', error));
-                await sendMessage(chatId, '添加群组失败,请联系管理员。');
-            }
-        } else {
-            // 其他新成员
-            console.log(formatLog({
-                member: member.username || member.first_name + ' (' + member.id + ')'
-            }));
-            await sendMessage(chatId, `欢迎 ${member.username || member.first_name} 加入群组!`);
-        }
-    }
-});
-
 // 处理机器人被移出群组
 bot.on('left_chat_member', async (msg) => {
     if (msg.left_chat_member.id === (await bot.getMe()).id) {
@@ -1062,6 +883,11 @@ async function handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup) {
             更新时间: new Date().toLocaleString()
         };
 
+        console.log(formatLog({
+            操作: '处理机器人添加',
+            群组信息: groupInfo
+        }));
+
         // 如果群组不存在,创建新群组
         if (!existingGroup) {
             const groupData = {
@@ -1072,77 +898,109 @@ async function handleBotAdded(msg, chatId, chatType, chatIdStr, existingGroup) {
             };
 
             try {
-                // 直接使用 SQL 插入或更新群组数据
-                const [result] = await pool.query(`
-                    INSERT INTO groups 
-                    (group_id, group_name, group_type, creator_id, is_active, last_join_time, 
-                     in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate, operators) 
-                    VALUES (?, ?, ?, ?, true, CURRENT_TIMESTAMP, 0.00, 1.0000, 0.00, 1.0000, '[]')
-                    ON DUPLICATE KEY UPDATE
-                    group_name = VALUES(group_name),
-                    group_type = VALUES(group_type),
-                    is_active = true,
-                    last_join_time = CURRENT_TIMESTAMP
-                `, [
-                    groupData.groupId,
-                    groupData.groupName,
-                    groupData.groupType,
-                    groupData.creatorId
-                ]);
+                // 检查群组是否已经存在
+                const [existingGroupCheck] = await pool.query(
+                    'SELECT * FROM groups WHERE group_id = ?',
+                    [chatIdStr]
+                );
+
+                if (existingGroupCheck && existingGroupCheck.length > 0) {
+                    console.log(formatLog({
+                        操作: '群组已存在,更新状态',
+                        群组ID: chatIdStr
+                    }));
+                    
+                    // 更新现有群组状态
+                    await pool.query(`
+                        UPDATE groups 
+                        SET is_active = true,
+                            group_name = ?,
+                            group_type = ?,
+                            last_join_time = CURRENT_TIMESTAMP
+                        WHERE group_id = ?
+                    `, [
+                        groupData.groupName,
+                        groupData.groupType,
+                        chatIdStr
+                    ]);
+                } else {
+                    // 创建新群组
+                    await pool.query(`
+                        INSERT INTO groups 
+                        (group_id, group_name, group_type, creator_id, is_active, last_join_time, 
+                         in_fee_rate, in_exchange_rate, out_fee_rate, out_exchange_rate, operators) 
+                        VALUES (?, ?, ?, ?, true, CURRENT_TIMESTAMP, 0.00, 1.0000, 0.00, 1.0000, '[]')
+                    `, [
+                        groupData.groupId,
+                        groupData.groupName,
+                        groupData.groupType,
+                        groupData.creatorId
+                    ]);
+                }
 
                 // 更新内存中的群组列表
                 if (!data.allowedGroups.includes(chatIdStr)) {
                     data.allowedGroups.push(chatIdStr);
                     saveData();
-                    console.log(`群组已添加 - ID: ${chatIdStr}, 名称: ${groupData.groupName}`);
                 }
 
-                try {
-                    // 发送欢迎消息
-                    await bot.sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。', {
-                        parse_mode: 'HTML'
-                    });
+                // 发送欢迎消息
+                await bot.sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。', {
+                    parse_mode: 'HTML'
+                });
 
-                    // 发送账单消息
-                    const billMessage = await generateBillMessage(chatId);
-                    if (billMessage) {
-                        await bot.sendMessage(chatId, billMessage, {
-                            parse_mode: 'HTML',
-                            reply_markup: generateInlineKeyboard(chatId)
-                        });
-                    }
-                } catch (messageError) {
-                    console.error('发送消息失败:', messageError.message);
+                // 发送账单消息
+                const billMessage = await generateBillMessage(chatId);
+                if (billMessage) {
+                    await bot.sendMessage(chatId, billMessage, {
+                        parse_mode: 'HTML',
+                        reply_markup: generateInlineKeyboard(chatId)
+                    });
                 }
+
+                console.log(formatLog({
+                    操作: '群组添加成功',
+                    群组ID: chatIdStr,
+                    群组名称: groupData.groupName
+                }));
+
             } catch (error) {
-                console.error('创建群组失败:', {
-                    错误: error.message,
+                console.error(formatLog({
+                    错误: '创建群组失败',
+                    详情: error.message,
                     群组ID: groupData.groupId
-                });
-                try {
-                    await bot.sendMessage(chatId, '添加群组失败,请联系管理员。', {
-                        parse_mode: 'HTML'
-                    });
-                } catch (messageError) {
-                    console.error('发送错误消息失败:', messageError.message);
+                }));
+                
+                // 检查是否是重复添加导致的错误
+                if (error.code === 'ER_DUP_ENTRY') {
+                    console.log(formatLog({
+                        操作: '检测到重复添加',
+                        群组ID: chatIdStr
+                    }));
+                    return;
                 }
+                
+                await bot.sendMessage(chatId, '添加群组失败,请联系管理员。', {
+                    parse_mode: 'HTML'
+                });
             }
         }
     } catch (error) {
-        console.error('处理群组添加失败:', error.message);
+        console.error(formatLog({
+            错误: '处理群组添加失败',
+            详情: error.message
+        }));
         await sendMessage(chatId, '添加群组失败,请联系管理员。');
     }
 }
 
 // 处理群组信息更新
-async function handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus) {
+async function handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus, newType) {
     const connection = await pool.getConnection();
     await connection.beginTransaction();
 
     try {
         // 更新群组ID和类型
-        const newType = chatType === 'private' ? 'private' :
-            chatType === 'supergroup' ? 'supergroup' : 'group';
         const oldGroupId = existingGroup.group_id;
 
         // 如果群组ID发生变化,更新所有相关记录
@@ -1303,26 +1161,83 @@ bot.on('my_chat_member', async (msg) => {
         const chatType = msg.chat.type;
         const chatIdStr = chatId.toString();
 
+        console.log(formatLog({
+            操作: '收到群组状态变更',
+            群组ID: chatIdStr,
+            群组名称: msg.chat.title,
+            旧状态: oldStatus,
+            新状态: newStatus,
+            群组类型: chatType
+        }));
+
+        // 定义群组类型
+        const newType = chatType === 'private' ? 'personal' : 
+                       chatType === 'supergroup' ? 'supergroup' : 'group';
+
         // 查找群组,同时检查新旧ID
         const existingGroup = await Group.findByGroupId(chatIdStr) ||
             await Group.findByGroupId(chatIdStr.replace('-', ''));
 
-        // 获取群组详细信息(如果机器人还在群组中)
-        if (newStatus !== 'kicked' && newStatus !== 'left') {
-            try {
-                const chatInfo = await bot.getChat(chatId);
-            } catch (error) {
-                console.log(formatLog('获取群组详细信息失败', error.message));
-            }
-        } else {
-            console.log('机器人已被移出群组,无法获取详细信息');
-        }
-
-        const newType = chatType === 'private' ? 'private' :
-            chatType === 'supergroup' ? 'supergroup' : 'group';
-            
         // 如果是机器人首次被添加到群组(从非成员变为成员)
         if (oldStatus === 'left' && newStatus === 'member') {
+            // 如果群组已存在且处于活跃状态,则发送欢迎消息
+            if (existingGroup && existingGroup.is_active) {
+                console.log(formatLog({
+                    操作: '机器人重新加入群组',
+                    群组ID: chatIdStr,
+                    群组名称: msg.chat.title || existingGroup.group_name
+                }));
+                
+                try {
+                    // 发送欢迎消息
+                    await bot.sendMessage(chatId, '感谢重新添加我为群组成员!', {
+                        parse_mode: 'HTML'
+                    });
+                    
+                    // 发送账单消息
+                    const billMessage = await generateBillMessage(chatId);
+                    if (billMessage) {
+                        await bot.sendMessage(chatId, billMessage, {
+                            parse_mode: 'HTML',
+                            reply_markup: generateInlineKeyboard(chatId)
+                        });
+                    }
+                } catch (error) {
+                    console.error(formatLog({
+                        错误: '发送消息失败',
+                        详情: error.message,
+                        群组ID: chatIdStr
+                    }));
+                }
+                return;
+            }
+
+            // 检查邀请者是否已存在于用户表中
+            const [existingUser] = await pool.query(
+                'SELECT * FROM users WHERE id = ?',
+                [msg.from.id]
+            );
+
+            // 如果用户不存在,则创建新用户
+            if (!existingUser || existingUser.length === 0) {
+                // 生成唯一的用户名
+                const username = msg.from.username || `user_${msg.from.id}`;
+                
+                await pool.query(`
+                    INSERT INTO users 
+                    (id, username, password, role) 
+                    VALUES (?, ?, '', 'user')
+                `, [msg.from.id, username]);
+
+                console.log(formatLog({
+                    操作: '新增用户',
+                    ID: msg.from.id,
+                    用户名: username,
+                    角色: 'user',
+                    时间: new Date().toLocaleString()
+                }));
+            }
+
             if (!existingGroup) {
                 await handleBotAdded(msg, chatId, chatType, chatIdStr, null);
             } else if (existingGroup.group_type !== newType) {
@@ -1331,7 +1246,8 @@ bot.on('my_chat_member', async (msg) => {
         }
 
         if (existingGroup) {
-            await handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus);
+            // 传递 newType 到 handleGroupUpdate 函数
+            await handleGroupUpdate(msg, chatId, chatType, chatIdStr, existingGroup, newStatus, newType);
         } else if (newStatus === 'member') {
             // 如果是新群组且机器人被添加为成员
             await handleBotAdded(msg, chatId, chatType, chatIdStr, null);

+ 0 - 1
admin/数据文件路径

@@ -46,7 +46,6 @@
     "-1002249794545",
     "-1002676340401",
     "-4750899185",
-    "-4779509671",
     "-4666274251"
   ]
 }