这是在我使用的聊天室中运行主持人机器人的代码的一部分。代码的这一部分是批准某人的请求,但每当我使用该命令时,我都会收到此未绑定的本地错误... 我已经经历了这么多次,我无法弄清楚为什么我会得到它。
def approveCam(room, identifier):
if not room.bpass:
return
if type(identifier) in [str, unicode, int]:
user = room._getUser(identifier)
if not user:
return "User " + str(identifier) + " was not found..."
if user.broadcasting:
return
room._sendCommand("privmsg", [room._encodeMessage("/allowbroadcast " + room.bpass),
"#0,en" + "n" + str(user.id) + "-" + user.nick])
问题似乎是“if user.broadcasting:”
代码在此前的机器人版本上工作
def approveCam(room, user):
if type(user) is str or type(user) is unicode:
nick = user
user = room._getUser(user)
if not user:
return "User "+nick+" was not found..."
if not room.bpass:
return
room._sendCommand("privmsg", [room._encodeMessage("/allowbroadcast "+room.bpass),
"#0,en"+"n"+ user.id+"-"+user.nick])
这是我尝试运行命令时在命令提示符下的响应。
Traceback (most recent call last):
File "C:\Users\Ejah\Downloads\Desktop\Tunebot-Master\tinychat.py", line 1262
in onMessage
SETTINGS['onMessageExtend'](self, user, msg)
File "tunebot.py", line 1316, in onMessageExtended
handleUserCommand(room, user, msg)
File "tunebot.py", line 1722, in handleUserCommand
res = botterCommands(room, userCmd, userArgsStr, userArgs, target,
File "tunebot.py", line 2786, in botterCommands
res = approveCam(room, user)
File "tunebot.py", line 4043, in approveCam
if user.broadcasting:
UnboundLocalError: local variable 'user' referenced before assignment"
答案 0 :(得分:0)
更新您的代码,以便在identifier
属于无效类型时引发错误,并且一切都将变得清晰:
def approveCam(room, identifier):
if not room.bpass:
return
if type(identifier) in [str, unicode, int]:
user = room._getUser(identifier)
if not user:
return "User " + str(identifier) + " was not found..."
else:
raise ValueError('Invalid type for identifier')
if user.broadcasting:
return
room._sendCommand("privmsg", [room._encodeMessage("/allowbroadcast " + room.bpass),
"#0,en" + "n" + str(user.id) + "-" + user.nick])
答案 1 :(得分:0)
user.broadcasting - This is not correct
此时用户不存在,因此解释器不允许这样做。您必须在使用之前初始化局部变量。
使用户成为具有一定价值的全局变量。
答案 2 :(得分:0)
可能if type(identifier) in [str, unicode, int]:
为False
,因此if
的正文未执行,user
永远不会被初始化。
如果可能,请在第二个user
之前初始化if
,或重新考虑您的代码。
P.S。不要使用getter和setter! Python不是Java,如果你真的需要使用它,请改用属性。