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

Discord.py Stable Diffusion机器人Y/N参数选择功能异常求助

问题解决:Discord机器人Stable Diffusion参数构建错误

问题根源

直接将用户输入的"y"/"n"通过bool()转换是错误的——Python中所有非空字符串都会被解析为True,哪怕输入是"n",bool("n")的结果依然是True,导致判断条件始终成立,参数会被强制添加。

修复方案

修改用户响应的处理逻辑,针对布尔类型参数单独判断输入内容,同时处理整数类型的空输入场景:

predetermined_arguments = [
    {"name": "quoted_argument", "question": "Enter the quoted argument:", "type": str},
    {"name": "plms_option", "question": "Use --plms option? (y/n)", "type": bool},
    {"name": "skip_grid_option", "question": "Use --skip_grid option? (y/n)", "type": bool},
    {"name": "n_samples_value", "question": "Enter the value for --n_samples (or leave empty for 0):", "type": int}
]

@bot.command()
async def request(ctx):
    try:
        user_responses = {}
        for arg in predetermined_arguments:
            question = arg["question"]
            response = await ask_question(ctx, question)
            # 超时返回None时直接终止请求
            if response is None:
                return
            
            arg_type = arg["type"]
            if arg_type == bool:
                # 不区分大小写判断y/n,转换为布尔值
                user_responses[arg["name"]] = response.strip().lower() == "y"
            elif arg_type == int:
                # 处理空输入,默认设为0
                if not response.strip():
                    user_responses[arg["name"]] = 0
                else:
                    user_responses[arg["name"]] = int(response)
            else:
                # 字符串类型直接处理
                user_responses[arg["name"]] = str(response)

        # Construct the bash command based on user responses
        bash_command = ["run.sh"]
        if user_responses["quoted_argument"]:
            bash_command.append(f'"{user_responses["quoted_argument"]}"')
        if user_responses["plms_option"]:
            bash_command.append('--plms')
        if user_responses["skip_grid_option"]:
            bash_command.append('--skip_grid')
        if user_responses["n_samples_value"]:
            bash_command.extend(['--n_samples', str(user_responses["n_samples_value"])])
            
        # Run the bash script with the arguments
        subprocess.run(bash_command, check=True)
        await ctx.send("Request processed successfully!")
    except Exception as e:
        await ctx.send(f"Error processing request: {e}")

async def ask_question(ctx, question):
    await ctx.send(question)

    def check(message):
        return message.author == ctx.author and message.channel == ctx.channel

    try:
        response = await bot.wait_for("message", check=check, timeout=60)
        return response.content
    except TimeoutError:
        await ctx.send("You took too long to respond. Request canceled.")
        return None

修改说明

  1. 布尔参数处理:不再用bool()转换输入,而是判断输入是否为小写的"y",匹配则为True,否则为False,支持不区分大小写的输入(比如"Y"/"N"也能正常识别)
  2. 整数参数空输入处理:用户留空时自动设为0,避免int("")触发 ValueError
  3. 超时终止逻辑:检测到ask_question返回None(用户超时)时直接终止请求,防止后续代码抛出异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:01:11