Checking if the user is connected before getting his team should without any doubt prevent that error. Every time you see an "invalid player X" error, it means that the user is not connected. Add the check in the beginning of the function and stop the code from going any further if it returns false.