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

Discord.py验证码机器人超时未完成验证无法自动踢人问题咨询

问题排查

你原代码的超时逻辑失效有3个核心原因:

  1. bot.wait_for('message')未设置超时参数,程序会永久阻塞等待用户发送消息,永远不会触发超时判定
  2. 末尾的asyncio.sleep(5)缺少await关键字,异步休眠不生效,且该段逻辑位置错误:不管用户是否验证成功都会执行踢人操作,和需求完全不符
  3. 验证码图片和答案没有对应绑定,任意正确验证码都能通过验证,存在安全漏洞
修正后完整代码
import discord
from discord.ext import commands
import random
import asyncio

intents = discord.Intents.default()
intents.members = True
intents.message_content = True # 必须开启消息内容权限,否则无法读取用户输入
bot = commands.Bot(command_prefix="+", intents=intents)

@bot.command()
async def setup(ctx):
  embed=discord.Embed(title="验证流程说明", 
  description="1. 进入验证频道使用命令 +verify\n2. 完成验证码验证后即可获得成员身份组进入服务器\n\n**你共有3次尝试机会,且需要在10秒内完成验证,否则会被自动踢出。如有问题请联系管理员**", color=0x0000FF)
  await ctx.send(embed=embed)

@bot.command(name='verify', pass_context = True)
async def verify(ctx):
    def check(m):
        return m.author == ctx.author and m.channel == ctx.message.channel
    
    # 调整为字典存储验证码图片和对应答案,避免串用
    captcha_map = {
        "captcha 6.png": "b3xpn",
        "captcha10.png": "2yggg",
        "captcha11.png": "ydg8n",
        "captcha2.png": "pp546",
        "captcha3.png": "fcne6",
        "captcha4.png": "cdfen",
        "captcha5.png": "4f8yp",
        "captcha7.png": "m8m4x",
        "captcha8.png": "pdyc8",
        "captcha9.png": "55w5c"
    }
    image_random = random.choice(list(captcha_map.keys()))
    correct_answer = captcha_map[image_random]

    await ctx.send(file=discord.File(image_random))
    await ctx.send('请输入图片中的验证码')

    passed = False
    for i in range(3):
        try:
            # 每次输入设置10秒超时,超时直接抛出异常
            guess = await bot.wait_for('message', check=check, timeout=10)
        except asyncio.TimeoutError:
            await ctx.send("验证超时,你已被踢出服务器")
            await asyncio.sleep(3)
            await ctx.author.kick(reason="验证超时")
            return
        
        if guess.content.strip() == correct_answer:
            await ctx.send('验证通过,欢迎加入服务器!')
            role = discord.utils.get(ctx.author.guild.roles, name="member")
            await ctx.author.add_roles(role)
            passed = True
            break
        else:
            await ctx.send(f"验证码错误,你还有{2-i}次尝试机会")
    
    if not passed:
        await ctx.send("错误次数已达上限,你已被踢出服务器")
        await asyncio.sleep(3)
        await ctx.author.kick(reason="验证码错误次数过多")
注意事项
  • 你需要在Discord开发者后台的Bot设置页开启Message Content Intent权限,否则机器人无法读取用户发送的消息内容
  • 确保机器人的角色权限高于你要分配的member角色,且拥有踢人权限
  • 代码中的超时时间可以自行调整,修改wait_for的timeout参数值即可,单位为秒

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:18:05