Spaces:
Paused
Paused
Download cogs/verification.py from QwertOs/DiscordBot: direct link, hf CLI and curl.
- Browser
- Download file 9.21 kB
-
https://huggingface.co/spaces/QwertOs/DiscordBot/resolve/main/cogs/verification.py
- Command line
-
hf download hf://spaces/QwertOs/DiscordBot/cogs/verification.py
-
curl -L -o verification.py https://huggingface.co/spaces/QwertOs/DiscordBot/resolve/main/cogs/verification.py
9.21 kB
| 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)) | |
| 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 | |
| ) | |
| 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 | |
| ) | |
| 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)) | |