所以我正在制作一个discordbot,并希望使用用户输入将名称添加到括号中。然而,我遇到了这个错误
Command raised an exception: UnboundLocalError: local variable 'msg1' referenced before assignment
我已经查看了有同样错误的问题,但我找不到任何与我的代码有关的问题,就在这里。
@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]')
time.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:
await ctx.send("You took too long")
return
player1 = driver.find_element(By.XPATH, '//*[@id="participant-1"]/div[3]/input')
for _ in range(7):
player1.send_keys('ue003')
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", time=9, check=lambda message: message.author == ctx.author)
except:
await ctx.send("You took too long")
return
player2 = driver.find_element(By.XPATH, '//*[@id="participant-2"]/div[3]/input')
for _ in range(7):
player2.send_keys('ue003')
player2.send_keys(msg1.content)
await ctx.send(f"Player 2 ({msg1.content} has been added)")
time.sleep(60)
您的代码给出了一个错误,因为msg1是在try块的作用域中定义的。如果你想在尝试块之外访问它,你需要做一些类似的事情
msg2 = None
try:
msg1 = await client.wait_for("message", time=9, check=lambda message: message.author == ctx.author)
msg2 = msg1
except:...
if (msg2 != None):
player2.send_keys(msg1.content)
await ctx.send(f"Player 2 ({msg1.content} has been added)")