如何让命令循环指定次数后终止?以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_countvariable 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 < 2to the existing condition, ensuring the loop runs a maximum of two times. - Fixed Input Check: The original
message != ""was comparing a DiscordMessageobject to a string, which won't work correctly. We now checkmessage.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
相关产品推荐
相关产品推荐

