//Settings---------------------------------------------------------------------------------
//*****************************************************************************************
var mail = "mail@mail.cz";
var account_id = "111-111-1111"; //if you have a script in your MCC account
/******************************************************************************************
Script:     Check url 404   
Version:    Adwords 27.02.2017
Created By: Stanislav Jilek [standajilek.cz]
/*****************************************************************************************/

function main() {
//Variables--------------------------------------------------------------------------------    
    var ads_url = [];
    var keywords_url = [];
    var sitelinks_url = [];
    var url = [];
    var url_404 = [];
    var count_200 = 0;
    var count_404 = 0;

//Mcc select-------------------------------------------------------------------------------  
    try
    {
        MccApp.select(MccApp.accounts().withIds([account_id]).get().next());
    } catch (error)
    {
    }

//Final urls------------------------------------------------------------------------------- 
//Ads  
    var ads = AdWordsApp.ads()
            .withCondition("CampaignStatus = ENABLED")
            .withCondition("AdGroupStatus = ENABLED")
            .withCondition("Status = ENABLED")
            .withCondition("CreativeFinalUrls != ''")
            .withCondition("Clicks>0")
            .forDateRange("YESTERDAY")
            .get()

    while (ads.hasNext())
    {
        ads_url.push(ads.next().urls().getFinalUrl());
    }

//Keywords  
    var keywords = AdWordsApp.keywords()
            .withCondition("CampaignStatus = ENABLED")
            .withCondition("AdGroupStatus = ENABLED")
            .withCondition("Status = ENABLED")
            .withCondition("FinalUrls != ''")
            .withCondition("Clicks>0")
            .forDateRange("YESTERDAY")
            .get()

    while (keywords.hasNext())
    {
        keywords_url.push(keywords.next().urls().getFinalUrl());
    }

//Sitelinks
    var sitelinks = AdWordsApp.extensions().sitelinks()
            .withCondition("Clicks>0")
            .forDateRange("YESTERDAY").get();

    while (sitelinks.hasNext())
    {
        sitelinks_url.push(sitelinks.next().urls().getFinalUrl());
    }

//Connection urls
    url = url.concat(ads_url, keywords_url, sitelinks_url);

//Remove duplicates------------------------------------------------------------------------
    var unique_url = url.filter(function (elem, index, self) {
        return index == self.indexOf(elem);
    });

//Test urls-------------------------------------------------------------------------------- 
    for (i = 0; i < unique_url.length; i++)
    {
        try
        {
            var response_code = UrlFetchApp.fetch(unique_url[i], {muteHttpExceptions: true}).getResponseCode();

            if (response_code == 404) {

                //Create label
                var label = [];
                if (ads_url.indexOf(unique_url[i]) != -1) {
                    label.push("ads");
                }
                if (keywords_url.indexOf(unique_url[i]) != -1) {
                    label.push("keywords");
                }
                if (sitelinks_url.indexOf(unique_url[i]) != -1) {
                    label.push("sitelinks");
                }
                label = label.join(", ");

                url_404.push("<tr><td nowrap>" + unique_url[i] + "</td><td nowrap>" + label + "</td></tr>");
                count_404 += 1;
            } else {
                count_200 += 1;
            }
            Utilities.sleep(200);

        } catch (error)
        {
        }

    }

//Logger----------------------------------------------------------------------------------  
    Logger.log("Count of unique urls -> " + (count_200 + count_404));
    Logger.log("Response code 200 -> " + count_200);
    Logger.log("Response code 404 -> " + count_404);

//Send mail-------------------------------------------------------------------------------
    var account_name = AdWordsApp.currentAccount().getName();

    if (url_404.length > 0) {
        url_404 = url_404.join("");
        MailApp.sendEmail({
            to: mail,
            subject: account_name + ': ERROR 404',
            htmlBody:
                    "<h2>" + account_name + "</h2>" +
                    "<h3>404 url:</h3>" +
                    "<table border='1' style='border-collapse: collapse;' cellpadding='5'>" +
                    "<tr bgcolor='#4fabe5'><th>Url</th><th>Label</th></tr>" +
                    url_404 + "</table>",
        });
    }

}