如何修复Discord命令中局部变量未赋值即引用的错误
解决Discord机器人中的UnboundLocalError:msg1引用前未赋值
错误根源
你的代码中第二个wait_for调用的参数名写错了——把timeout写成了time,导致超时功能完全失效。当出现超时以外的异常(或因参数错误导致wait_for无限等待最终触发其他异常)时,msg1未被赋值,但后续代码依然尝试访问msg1.content,从而引发UnboundLocalError。
修复方案
- 修正超时参数名:将第二个
wait_for中的time=9改为timeout=9,确保超时机制正常工作,超时后进入except块执行return,避免后续代码访问未赋值的msg1。 - 优化输入框清空逻辑:替换循环发送退格键的方式,直接调用
clear()方法清空输入框,更可靠高效。 - 替换同步sleep:将
time.sleep()改为await asyncio.sleep(),避免阻塞Discord机器人的异步事件循环。 - 修复字符串格式错误:第二个发送消息的字符串存在括号不匹配问题,修正为正确的格式。
- 明确异常捕获:替换裸
except为捕获特定的asyncio.TimeoutError,避免掩盖其他潜在问题。 - 添加资源清理:在所有退出路径中关闭浏览器,避免资源泄漏。
修复后的完整代码
import asyncio from selenium.webdriver.common.by import By from selenium import webdriver import discord from discord.ext import commands client = commands.Bot(command_prefix='!', intents=discord.Intents.all()) @client.command() async def bracketcreate(ctx): driver = webdriver.Chrome('./chromedriver.exe') driver.get("https://brackethq.com/maker/") teams = driver.find_element(By.XPATH, '/html/body/div[2]/div[1]/div[2]/div[1]') await asyncio.sleep(5) teams.click() await ctx.send("Send the name of player 1") try: msg = await client.wait_for("message", timeout=10, check=lambda message: message.author == ctx.author) except asyncio.TimeoutError: await ctx.send("You took too long") driver.quit() return player1 = driver.find_element(By.XPATH, '//*[@id="participant-1"]/div[3]/input') player1.clear() player1.send_keys(msg.content) await ctx.send(f"Player 1 ({msg.content}) has been added") await ctx.send("Send the name of player 2") try: msg1 = await client.wait_for("message", timeout=9, check=lambda message: message.author == ctx.author) except asyncio.TimeoutError: await ctx.send("You took too long") driver.quit() return player2 = driver.find_element(By.XPATH, '//*[@id="participant-2"]/div[3]/input') player2.clear() player2.send_keys(msg1.content) await ctx.send(f"Player 2 ({msg1.content}) has been added") await asyncio.sleep(60) driver.quit()
内容的提问来源于stack exchange,提问作者Alex is funny
相关产品推荐
相关产品推荐

