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

Discord机器人/verify验证码命令报错:TypeError缺失output参数求助

解决Discord机器人/verify命令的TypeError问题

错误原因

你遇到的TypeError是因为ImageCaptcha.write()方法必须传入两个必填参数:第一个是验证码文本,第二个是输出文件的路径。你的代码里只传了验证码文本captcha_text,漏掉了输出路径参数,所以触发报错。

完整修正方案

除了修复write()的参数问题,还要补全需求里的「已拥有角色无法执行命令」逻辑,同时优化验证码的发送和验证逻辑(避免多用户同时操作时的文件冲突,以及更严谨的消息检查):

修正后的完整代码

import asyncio
import random
import io
import discord
from captcha.image import ImageCaptcha

# 假设bot已经完成初始化配置
@bot.tree.command(name="verify", description="完成人机验证获取权限角色")
async def verify(interaction: discord.Interaction):
    # 1. 检查用户是否已拥有验证角色
    verify_role = discord.utils.get(interaction.guild.roles, name="Check")
    if verify_role in interaction.user.roles:
        await interaction.response.send_message("你已经完成过验证了!", ephemeral=True)
        return

    # 2. 生成7位验证码和图片
    captcha_text = str(random.randint(1000000, 9999999))
    image = ImageCaptcha(width=280, height=90)
    
    # 用BytesIO在内存生成图片,避免本地文件冲突
    img_bytes = io.BytesIO()
    image.write(captcha_text, img_bytes)
    img_bytes.seek(0)  # 重置文件指针到开头

    # 3. 回复用户并发送私信
    await interaction.response.send_message("请查看你的私信完成验证!", ephemeral=True)
    try:
        await interaction.user.send(
            "请输入下图中的7位验证码:",
            file=discord.File(fp=img_bytes, filename="captcha.png")
        )
    except discord.Forbidden:
        await interaction.followup.send("无法给你发送私信,请检查隐私设置!", ephemeral=True)
        return

    # 4. 等待用户输入验证码
    def check(msg):
        return msg.author == interaction.user and msg.guild is None

    try:
        msg = await bot.wait_for("message", check=check, timeout=60)
    except asyncio.TimeoutError:
        await interaction.user.send("验证码超时,请重新执行/verify命令!")
        return

    # 5. 验证结果处理
    if msg.content.strip() == captcha_text:
        await interaction.user.add_roles(verify_role)
        await interaction.user.send("验证成功!已为你添加权限角色。")
        await interaction.followup.send("验证成功!", ephemeral=True)
    else:
        await interaction.user.send("验证码错误,请重新执行/verify命令!")
        await interaction.followup.send("验证码错误,请重试!", ephemeral=True)

关键修改点说明

  • 修复write()参数:改用BytesIO在内存生成图片,既避免了本地文件路径的依赖,也解决了多用户同时操作时的文件覆盖问题;如果一定要存本地,正确写法是image.write(captcha_text, "captcha/CAPTCHA.png")(需确保captcha文件夹已存在)。
  • 添加角色检查:命令开头先判断用户是否已有目标角色,符合需求要求。
  • 优化消息检查:wait_for的check函数更严谨,确保只接收该用户的私信消息;添加了60秒超时处理,防止程序一直等待。
  • 错误处理:增加了无法发送私信的异常捕获,提升用户体验。
  • 适配官方规范:改用Discord推荐的Slash Command(@bot.tree.command)替代旧版前缀命令,符合当前API使用标准。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:55:22