How to flag an entity when it is created or updated?
You can use HOOK_entity_presave to trigger when node gets created. I updated code for you. Make sure that you change the capital letters to correct values.
function MODULENAME_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  // Check which content type would you like to flag.
  // You can use https://www.php.net/manual/en/function.in-array.php to check for 
  // multiple content types
  if (in_array($entity-&gt;bundle(), ['mycontentype1', 'mycontentype2'])) {
    $flag_id = 'yourflagname';
    
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service-&gt;getFlagById($flag_id);
    
    // Flag an entity with a specific flag.
    // https://www.drupal.org/docs/drupal-apis/entity-api/introduction-to-entity-api-in-drupal-8
    $flag_service-&gt;flag($flag, $entity);
  }
}