You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用discord.py实现验证码验证失败后禁言用户2小时并禁用按钮?

Discord.py 机器人验证码验证与禁言冷却实现方案

核心实现要点

  • 用字典存储用户冷却状态,记录禁言到期时间,避免重复触发操作
  • 所有按钮交互前先校验冷却状态,处于冷却期则直接终止操作
  • 验证码生成与校验绑定,输入不匹配时执行2小时禁言并更新冷却记录

完整代码示例

import discord
from discord.ui import Button, View, Modal, TextInput
import asyncio
from datetime import datetime, timedelta
# 替换为真实验证码生成逻辑,示例返回模拟文本与空图片对象
def generate_captcha():
    captcha_text = "K7X2P9"  # 实际需随机生成
    # 此处省略PIL生成带干扰线的验证码图片步骤
    return captcha_text, None

# 存储用户冷却状态:key=用户ID,value=冷却到期时间
cool_down_users = {}

class InitialButton(View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="身份验证", style=discord.ButtonStyle.green)
    async def verify_trigger(self, interaction: discord.Interaction, button: Button):
        user_id = interaction.user.id
        # 检查是否处于冷却期
        if user_id in cool_down_users and datetime.now() < cool_down_users[user_id]:
            await interaction.response.send_message("你处于冷却期,暂时无法操作", ephemeral=True)
            return

        # 生成验证码并构建Embed
        captcha_text, captcha_image = generate_captcha()
        embed = discord.Embed(title="完成验证码验证", description="输入图片中的字符")
        # 实际项目中添加图片附件
        # file = discord.File(captcha_image, filename="captcha.png")
        # embed.set_image(url="attachment://captcha.png")
        # view = CaptchaView(captcha_text)
        # await interaction.response.send_message(embed=embed, file=file, view=view, ephemeral=True)
        
        # 模拟无图片场景,实际替换为带图片逻辑
        embed.description = f"示例验证码:{captcha_text}"
        view = CaptchaView(captcha_text)
        await interaction.response.send_message(embed=embed, view=view, ephemeral=True)

class CaptchaModal(Modal, title="输入验证码"):
    def __init__(self, correct_captcha):
        super().__init__()
        self.correct_captcha = correct_captcha
        self.captcha_input = TextInput(label="验证码", placeholder="输入图片中的字符", max_length=8)
        self.add_item(self.captcha_input)

    async def on_submit(self, interaction: discord.Interaction):
        user_input = self.captcha_input.value.strip().upper()
        if user_input != self.correct_captcha.upper():
            # 执行2小时禁言并记录冷却时间
            try:
                await interaction.user.timeout(timedelta(hours=2), reason="验证码输入错误")
                cool_down_users[interaction.user.id] = datetime.now() + timedelta(hours=2)
                await interaction.response.send_message("验证码错误,已被禁言2小时", ephemeral=True)
            except discord.Forbidden:
                await interaction.response.send_message("权限不足,无法执行禁言", ephemeral=True)
        else:
            await interaction.response.send_message("验证成功!", ephemeral=True)

class CaptchaView(View):
    def __init__(self, correct_captcha):
        super().__init__(timeout=60)
        self.correct_captcha = correct_captcha

    @discord.ui.button(label="输入验证码", style=discord.ButtonStyle.blurple)
    async def open_modal(self, interaction: discord.Interaction, button: Button):
        user_id = interaction.user.id
        # 检查冷却状态
        if user_id in cool_down_users and datetime.now() < cool_down_users[user_id]:
            await interaction.response.send_message("你处于冷却期,暂时无法操作", ephemeral=True)
            return
        # 弹出验证码输入模态框
        modal = CaptchaModal(self.correct_captcha)
        await interaction.response.send_modal(modal)

# 初始化机器人
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = discord.Bot(intents=intents)

@bot.event
async def on_ready():
    print(f"已登录:{bot.user}")
    # 发送初始按钮到指定频道,替换为你的频道ID
    target_channel = bot.get_channel(1234567890)
    if target_channel:
        await target_channel.send("点击下方按钮开始身份验证", view=InitialButton())

# 运行机器人,替换为你的TOKEN
bot.run("YOUR_BOT_TOKEN")

关键逻辑说明

  1. 冷却状态校验:所有按钮回调第一步检查cool_down_users字典,若用户仍在冷却期则直接拒绝操作。
  2. 验证码生成:generate_captcha需替换为真实图片生成逻辑(如用PIL生成带干扰元素的验证码图片),返回验证码文本与图片数据。
  3. 禁言与冷却绑定:验证码不匹配时执行禁言,并将用户冷却到期时间写入字典,确保2小时内无法触发任何按钮交互。
  4. 模态框交互:点击验证码按钮后弹出模态框,输入完成后对比验证码,执行对应结果逻辑。

内容的提问来源于stack exchange,提问作者SKB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:25:16