Discord.py打字竞速机器人匹配异常求助:输入内容与题目一致却判定错误
Hey there! Let's figure out why your typerace bot is saying your answer is wrong even when you type it perfectly. The most likely culprit here is unhandled newline characters from your text file—here's how to fix it:
The Root Cause
When you read lines from typerace_questions.txt, each line includes the trailing newline character (\n or \r\n depending on your OS). So when you store question = tr_questions[num-1], that variable has an invisible newline at the end. When you type the answer in Discord, you don't include that newline, so guess.content == question will always return False.
Plus, there's a small bug in your random index selection: random.randint(0, tr_total_q) can return tr_total_q (since randint is inclusive), which would make num-1 = -1 when num=0—that's a guaranteed index error waiting to happen!
Fixes to Apply
1. Clean Up File Input
Instead of reading lines raw, strip off any leading/trailing whitespace (including newlines) from each question. Use a with statement to handle file closing automatically—it's safer and cleaner:
with open("typerace_questions.txt", 'r') as tr_questions_file: tr_questions = [line.strip() for line in tr_questions_file] tr_total_q = len(tr_questions) # Use actual number of questions instead of hardcoding 10
2. Simplify Random Question Selection
Skip the index math entirely and use random.choice() to pick a random question directly—no more risk of index errors:
question = random.choice(tr_questions)
3. Full Corrected Code
Here's your updated bot code with all fixes applied:
import discord from discord.ext import commands import time import asyncio import random client = commands.Bot(command_prefix='>', help_command=None) # Load and clean typerace questions with open("typerace_questions.txt", 'r') as tr_questions_file: tr_questions = [line.strip() for line in tr_questions_file] tr_total_q = len(tr_questions) @client.command(aliases=['tr', 'typeRace']) async def typerace(ctx): starttime = time.time() question = random.choice(tr_questions) print(question) timer = 30.0 embed = discord.Embed(title="TYPE RACE", description=f"{question}") await ctx.reply(embed=embed) def is_correct(msg): return msg.author == ctx.author try: guess = await client.wait_for('message', check=is_correct, timeout=timer) print(guess.content) except asyncio.TimeoutError: return await ctx.reply("You took too long to type :(") if guess.content == question: fintime = time.time() total = fintime - starttime await ctx.send(f"You got it!!\nYou got it in {round(total)} seconds") else: await ctx.send(f"Nope, that is not correct!!\nTry again using ``>tr``") client.run(token)
Quick Checks
- Double-check that your
typerace_questions.txtdoesn't have extra spaces at the end of lines (thestrip()method will handle this anyway, but it's good practice) - Test with a single line in the text file first to confirm the fix works
内容的提问来源于stack exchange,提问作者09ghostrider

