File size: 9,205 Bytes
2fd3032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import discord
from discord.ext import commands
import structlog
import random
import string
from datetime import datetime, timedelta

logger = structlog.get_logger()


class VerificationModal(discord.ui.Modal, title="身份验证"):
    def __init__(self, bot):
        super().__init__()
        self.bot = bot
    
    code = discord.ui.TextInput(
        label="验证码",
        placeholder="请输入你收到的6位验证码",
        required=True,
        min_length=6,
        max_length=6
    )
    
    async def on_submit(self, interaction: discord.Interaction):
        user_id = interaction.user.id
        input_code = self.code.value.upper()
        
        conn = self.bot.pool
        
        # 查询用户的验证记录
        cursor = await conn.execute(
            "SELECT * FROM user_verifications WHERE user_id = ?",
            (user_id,)
        )
        record = await cursor.fetchone()
        
        if not record:
            await interaction.response.send_message(
                "❌ 未找到验证请求。请先使用 `/verify` 命令开始验证流程。",
                ephemeral=True
            )
            return
        
        # 检查是否已验证
        if record['verified']:
            await interaction.response.send_message(
                "✅ 你已经完成验证了!",
                ephemeral=True
            )
            return
        
        # 检查验证码是否正确
        if record['verification_code'] != input_code:
            # 增加尝试次数
            new_attempts = record['attempts'] + 1
            await conn.execute(
                "UPDATE user_verifications SET attempts = ? WHERE user_id = ?",
                new_attempts, user_id
            )
            
            if new_attempts >= 3:
                await interaction.response.send_message(
                    "❌ 验证码错误次数过多。请使用 `/verify` 重新获取验证码。",
                    ephemeral=True
                )
            else:
                remaining = 3 - new_attempts
                await interaction.response.send_message(
                    f"❌ 验证码错误。你还剩 {remaining} 次尝试机会。",
                    ephemeral=True
                )
            return
        
        # 验证成功
        verified_role = discord.utils.get(interaction.guild.roles, name="Verified") or \
                       discord.utils.get(interaction.guild.roles, name="已验证")
        
        if verified_role:
            await interaction.user.add_roles(verified_role)
        
        # 更新数据库
        await conn.execute(
            """UPDATE user_verifications 

               SET verified = 1, verified_at = ? 

               WHERE user_id = ?""",
            datetime.utcnow().isoformat(), user_id
        )
        
        logger.info(f'用户 {interaction.user.name} 验证成功')
        
        embed = discord.Embed(
            title="✅ 验证成功!",
            description=f"欢迎 {interaction.user.mention}!你现在可以访问服务器的所有频道了。",
            color=0x00ff00
        )
        
        await interaction.response.send_message(embed=embed, ephemeral=True)


class VerificationCog(commands.Cog, name="Verification"):
    """用户验证系统"""
    
    def __init__(self, bot):
        self.bot = bot
        self.logger = logger
    
    def generate_verification_code(self, length=6):
        """生成随机验证码"""
        return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
    
    @discord.app_commands.command(name="verify", description="开始身份验证流程")
    async def verify(self, interaction: discord.Interaction):
        """开始验证流程"""
        user_id = interaction.user.id
        conn = self.bot.pool
        
        # 检查用户是否已经验证
        cursor = await conn.execute(
            "SELECT * FROM user_verifications WHERE user_id = ?",
            (user_id,)
        )
        record = await cursor.fetchone()
        
        if record and record['verified']:
            await interaction.response.send_message(
                "✅ 你已经完成验证了!",
                ephemeral=True
            )
            return
        
        # 生成新的验证码
        code = self.generate_verification_code()
        
        # 保存或更新验证记录
        if record:
            await conn.execute(
                """UPDATE user_verifications 

                   SET verification_code = ?, attempts = 0 

                   WHERE user_id = ?""",
                code, user_id
            )
        else:
            await conn.execute(
                """INSERT INTO user_verifications (user_id, verification_code, attempts) 

                   VALUES (?, ?, 0)""",
                user_id, code
            )
        
        # 发送验证码给用户(私信)
        try:
            embed = discord.Embed(
                title="🔐 身份验证",
                description=f"你的验证码是:**{code}**\n\n请点击下面的按钮并输入此验证码完成验证。",
                color=0x5865F2
            )
            embed.set_footer(text="验证码有效期为10分钟")
            
            view = discord.ui.View(timeout=600)  # 10分钟超时
            view.add_item(discord.ui.Button(
                label="输入验证码",
                style=discord.ButtonStyle.primary,
                custom_id="verify_modal"
            ))
            
            await interaction.user.send(embed=embed, view=view)
            
            await interaction.response.send_message(
                "✅ 验证码已发送到你的私信!请查收。",
                ephemeral=True
            )
            
        except discord.Forbidden:
            await interaction.response.send_message(
                "❌ 无法发送私信。请确保你允许接收来自服务器成员的私信。",
                ephemeral=True
            )
    
    @discord.app_commands.command(name="verifysetup", description="设置验证系统(仅管理员)")
    @commands.has_permissions(manage_guild=True)
    async def verify_setup(self, interaction: discord.Interaction):
        """设置验证系统"""
        # 创建 Verified 角色(如果不存在)
        verified_role = discord.utils.get(interaction.guild.roles, name="Verified")
        if not verified_role:
            verified_role = await interaction.guild.create_role(
                name="Verified",
                color=discord.Color.green(),
                reason="验证系统设置"
            )
        
        # 创建验证说明频道
        verify_channel = discord.utils.get(interaction.guild.text_channels, name="verify-here")
        if not verify_channel:
            overwrites = {
                interaction.guild.default_role: discord.PermissionOverwrite(
                    send_messages=False,
                    view_channel=True
                ),
                interaction.guild.me: discord.PermissionOverwrite(
                    send_messages=True,
                    view_channel=True
                )
            }
            
            verify_channel = await interaction.guild.create_text_channel(
                name="verify-here",
                overwrites=overwrites,
                reason="验证系统设置"
            )
        
        # 发送验证说明消息
        embed = discord.Embed(
            title="🔐 身份验证",
            description="欢迎来到服务器!为了访问所有频道,你需要完成身份验证。\n\n"
                       "**验证步骤:**\n"
                       "1. 使用 `/verify` 命令\n"
                       "2. 查看你的私信获取验证码\n"
                       "3. 输入验证码完成验证\n\n"
                       "如有问题,请联系管理员。",
            color=0x5865F2
        )
        
        view = discord.ui.View()
        view.add_item(discord.ui.Button(
            label="开始验证",
            style=discord.ButtonStyle.primary,
            emoji="🔐"
        ))
        
        await verify_channel.send(embed=embed, view=view)
        
        await interaction.response.send_message(
            f"✅ 验证系统已设置完成!\n- 创建了角色: {verified_role.mention}\n- 创建了频道: {verify_channel.mention}",
            ephemeral=True
        )
    
    @verify.error
    async def verify_error(self, interaction: discord.Interaction, error):
        """处理验证命令的错误"""
        if isinstance(error, discord.app_commands.MissingPermissions):
            await interaction.response.send_message(
                "❌ 你没有权限执行此命令。",
                ephemeral=True
            )


async def setup(bot):
    await bot.add_cog(VerificationCog(bot))