How to write a script if water sensor comes into contact with water for more than 2 mins and LED lights up
Should the LED be latched (stay on forever, once it's on), or go out if the sensor later detects no water? I'll assume the latter. Here's an (untested) state machine that should give you a good start. It keeps track of whether water was already seen, when it started, and whether it is seen now. There is some redundant switching of the LED; removing that (if desired) "is left as an exercise for the reader".

#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4 

#define TWOMIN (2*60*1000L)

bool isWater, wasWater = false;    // true =&gt; currently/were seeing water
uint32_t WaterStart_ms = 0;        // time first saw water


void setup() {
  pinMode(watersensor, INPUT_PULLUP);  // pullup for testing w/a button
  pinMode(led, OUTPUT);
}


void loop()
{
  // Is there water?
  isWater = !digitalRead(watersensor);     // read sensor

  if ( isWater ) {
    if ( !wasWater ){
      // First water: note the time
      WaterStart_ms = millis();
      wasWater = true;
    }
    else {
      // Water continues; time to light LED?
      if ( (millis() - WaterStart_ms) &gt;= TWOMIN )
        digitalWrite(led, HIGH);
    }
  }
  else {
    // No water; LED off
    wasWater = false;
    digitalWrite(led, LOW);
  }
  delay(300);
}


Update:

Added wasWater = true; at line 27. The delay(300) at line 40 isn't necessary. Ran correctly when I tested it with a button (also negative logic) for the sensor.


  the light lights up randomly.


See if your sensor gives solid responses (try printing its output in loop() ). If it dithers around transitions, you may need to wait for some number of readings in a row that are opposite to the previous sensor state before you accept its new state as real.