When you want to check for a new nearest enemy after moving to a flag, make sure you check for an enemy before attacking or calling a spell.  That is the error you are getting, you don’t have an enemy to cast the spell against.  Keep in mind that by calling the hero.findNearestEnemy() after you did a check for hero.canCast("chain-lightning", enemy) you may be finding a new enemy that your hero can’t cast the spell against.  Using the same variable name for each check could cause you some problems too later on.
if enemy:
    hero.cleave(enemy) # or hero.cast("chain-lightning", enemy)
One other detail, after you call the first line at the top,
nearest = hero.findNearestEnemy()
You don’t need to check for a new enemy every time unless you want to check again after you move to the flags.
elif nearest and hero.distanceTo(nearest) < 10:
    enemy = hero.findNearestEnemy() # no need to check for a new enemy
    hero.attack(enemy) # use the nearest variable that you are checking
            thank you, it now works 
