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

如何让命令循环指定次数后终止?以Discord机器人代码为例

Limit Discord Bot Loop to 2 Iterations

Got it! To prevent your bot from spamming the chat by limiting the loop to exactly 2 iterations, you can add a counter variable to track how many times the loop has executed. Here's the modified version of your code with explanations:

# Initialize a counter to track loop iterations
loop_count = 0

# Update the while condition to include the loop limit
while answer.lower() != "proceed" and answer.lower() != "return" and loop_count < 2:
    await ctx.send("Only enter 'proceed' or 'return'!")
    await ctx.send('''Are you sure you want to nuke this channel? This will completely erase all messages from it! type proceed to continue, and return to return. ''')
    
    # Fixed the input check: compare message content (stripped) to empty string, not the message object itself
    answer = await client.wait_for(
        'message', 
        check=lambda message: message.author == ctx.author and message.content.strip() != ""
    )
    answer = answer.content
    
    # Increment the counter after each loop iteration
    loop_count += 1

# Optional: Notify user if process was aborted due to too many invalid attempts
if loop_count >= 2 and answer.lower() not in ["proceed", "return"]:
    await ctx.send("Too many invalid attempts. Aborting channel nuke process.")

Key Changes Explained:

  • Loop Counter: The loop_count variable starts at 0 and increments after each iteration. The loop will stop once this counter reaches 2, regardless of the user's input.
  • Updated While Condition: Added loop_count < 2 to the existing condition, ensuring the loop runs a maximum of two times.
  • Fixed Input Check: The original message != "" was comparing a Discord Message object to a string, which won't work correctly. We now check message.content.strip() != "" to ensure the user sent a non-empty message.
  • Post-Loop Notification: The optional final check lets the user know the process was aborted if they failed to enter valid input after two tries.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:57:32