This is part of a code that runs a moderator bot in a chatroom i use. This section of the code is to approve someone's request to cam up but whenever I use the command I get this unbound local error... I have gone through this so many times and I can't figure out why I'm getting it.
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])
The problem seems to be at "if user.broadcasting:"
the code worked on a previous version of the bot like this
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])
and here is the response i get in command prompt when i try to run the command.
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"
Update your code to raise an error when identifier
is of an invalid type and all will become clear:
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])
user.broadcasting - This is not correct
At this point user does not exist and hence the interpreter won't allow that. You must initialise local variables before using them.
Make user a global variable with some value to it.
Probably if type(identifier) in [str, unicode, int]:
is False
, so the body of the if
is not executed and user
is never inizialized.
Initialize user
before the second if
if possible, or rethink your code.
PS Don't use getter and setter! Python is not Java, if you really need to use them, use a property instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.