def update_user_message_flags(message: Message, ums: Iterable[UserMessage]) -> None:
    wildcard = message.mentions_wildcard
    mentioned_ids = message.mentions_user_ids
    ids_with_alert_words = message.user_ids_with_alert_words
    changed_ums: Set[UserMessage] = set()

    def update_flag(um: UserMessage, should_set: bool, flag: int) -> None:
        if should_set:
            if (not (um.flags & flag)):
                um.flags |= flag
                changed_ums.add(um)
        elif (um.flags & flag):
            um.flags &= (~ flag)
            changed_ums.add(um)
    for um in ums:
        has_alert_word = (um.user_profile_id in ids_with_alert_words)
        update_flag(um, has_alert_word, UserMessage.flags.has_alert_word)
        mentioned = (um.user_profile_id in mentioned_ids)
        update_flag(um, mentioned, UserMessage.flags.mentioned)
        update_flag(um, wildcard, UserMessage.flags.wildcard_mentioned)
    for um in changed_ums:
        um.save(update_fields=['flags'])
def update_user_message_flags(message: Message, ums: Iterable[UserMessage]) -> None:
    wildcard = message.mentions_wildcard
    mentioned_ids = message.mentions_user_ids
    ids_with_alert_words = message.user_ids_with_alert_words
    changed_ums: Set[UserMessage] = set()

    def update_flag(um: UserMessage, should_set: bool, flag: int) -> None:
        if should_set:
            if (not (um.flags & flag)):
                um.flags |= flag
                changed_ums.add(um)
        elif (um.flags & flag):
            um.flags &= (~ flag)
            changed_ums.add(um)
    for um in ums:
        has_alert_word = (um.user_profile_id in ids_with_alert_words)
        update_flag(um, has_alert_word, UserMessage.flags.has_alert_word)
        mentioned = (um.user_profile_id in mentioned_ids)
        update_flag(um, mentioned, UserMessage.flags.mentioned)
        update_flag(um, wildcard, UserMessage.flags.wildcard_mentioned)
    for um in changed_ums:
        um.save(update_fields=['flags'])