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

如何在单行for循环中添加break?Discord Bot循环截断问题

解决Discord Bot自动补全超过25项报错的问题

你可以通过先过滤符合条件的物品,再截取前25项的方式限制返回数量,避免触发报错。修正后的代码如下:

from typing import List
import discord
from discord import app_commands

async def fruit_autocomplete(
    interaction: discord.Interaction,
    current: str,
) -> List[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    # 先筛选匹配的水果,再截取前25个生成Choice对象
    matched_fruits = [fruit for fruit in fruits if current.lower() in fruit.lower()]
    return [
        app_commands.Choice(name=fruit, value=fruit)
        for fruit in matched_fruits[:25]
    ]

也可以把逻辑合并到单个列表推导式中,用enumerate控制循环次数:

async def fruit_autocomplete(
    interaction: discord.Interaction,
    current: str,
) -> List[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    return [
        app_commands.Choice(name=fruit, value=fruit)
        for idx, fruit in enumerate(fruits)
        if current.lower() in fruit.lower() and idx < 25
    ]

说明

  • Discord自动补全接口最多仅支持25个选项,超出该数量会直接触发报错,因此必须对结果做截断处理。
  • 第一种方案逻辑更清晰:先筛选所有匹配项,再取前25个生成Choice,确保返回数量不超限。
  • 第二种方案在循环时直接判断索引,达到25次后停止迭代,最终效果和第一种一致——仅返回匹配结果中的前25项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:31:14