Youtube subscribers and/or views?

Hi guys,
Trying to find a script or app that can get the number of subscribers or views from a youtube channel? Any suggestions?

Here you go.

First you need an API key for YouTube. For that you need the Google Developer Console and a project.

Create a Project in Google Developer Console:

  • Go to the Google Developer Console.
  • Create a new project.
  • Navigate to the “APIs & Services” > “Library”.
  • Search for “YouTube Data API v3” and enable it.
  • Go to “Credentials” and create an API key.

Once you got the API credentials, then you need this Homey Script:

const apiKey = 'Insert Your API Key Here'; // Replace with your YouTube API key
const channelId = 'UCmOtm5LaBo-wKEEZDhzA0XQ'; // Replace with the YouTube channel ID you want. This one is Homey's channel.

async function fetchSubscriberCount(channelId, apiKey) {
    const url = `https://www.googleapis.com/youtube/v3/channels?part=statistics&id=${channelId}&key=${apiKey}`;
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        const subscriberCount = data.items[0].statistics.subscriberCount;
        return `Subscriber Count: ${subscriberCount}`;
    } catch (error) {
        console.error('Error fetching subscriber count:', error);
        return 'Error fetching subscriber count.';
    }
}

fetchSubscriberCount(channelId, apiKey).then(result => {
    console.log(result);
});
1 Like

Nice @Daxziz , thank you, based on your example I was able to extend it little bit more…

script_result

const apiKey = 'Insert Your API Key Here'; // Replace with your YouTube API key
const channelId = 'UCmOtm5LaBo-wKEEZDhzA0XQ'; // Replace with the YouTube channel ID you want. This one is Homey's channel.

async function fetchChannelStatistics(channelId, apiKey) {
    const url = `https://www.googleapis.com/youtube/v3/channels?part=statistics&id=${channelId}&key=${apiKey}`;
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        const statistics = data.items[0].statistics;
        const subscriberCount = parseInt(statistics.subscriberCount, 10);
        const videoCount = parseInt(statistics.videoCount, 10);
        const viewCount = await fetchTotalViewCount(channelId, apiKey);
        
        return {
            subscriberCount: subscriberCount,
            videoCount: videoCount,
            viewCount: viewCount
        };
    } catch (error) {
        console.error('Error fetching channel statistics:', error);
        return {
            subscriberCount: -1,
            videoCount: -1,
            viewCount: -1
        };
    }
}

async function fetchTotalViewCount(channelId, apiKey) {
    const playlistId = await fetchUploadPlaylistId(channelId, apiKey);
    const videos = await fetchVideosFromPlaylist(playlistId, apiKey);
    let totalViewCount = 0;
    
    for (const video of videos) {
        const videoStats = await fetchVideoStatistics(video.id, apiKey);
        totalViewCount += parseInt(videoStats.viewCount, 10);
    }

    return totalViewCount;
}

async function fetchUploadPlaylistId(channelId, apiKey) {
    const url = `https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id=${channelId}&key=${apiKey}`;
    const response = await fetch(url);
    const data = await response.json();
    return data.items[0].contentDetails.relatedPlaylists.uploads;
}

async function fetchVideosFromPlaylist(playlistId, apiKey) {
    const url = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${playlistId}&maxResults=50&key=${apiKey}`;
    const response = await fetch(url);
    const data = await response.json();
    return data.items.map(item => ({ id: item.snippet.resourceId.videoId }));
}

async function fetchVideoStatistics(videoId, apiKey) {
    const url = `https://www.googleapis.com/youtube/v3/videos?part=statistics&id=${videoId}&key=${apiKey}`;
    const response = await fetch(url);
    const data = await response.json();
    return data.items[0].statistics;
}

async function getYouTubeChannelStatistics() {
    return await fetchChannelStatistics(channelId, apiKey);
}

async function main() {
    try {
        const result = await getYouTubeChannelStatistics();
        
        // Output for script AND card
        await tag('subscriberCount', result.subscriberCount);
        await tag('videoCount', result.videoCount);
        await tag('viewCount', result.viewCount);

        console.log('Subscriber Count:', result.subscriberCount);
        console.log('View Count:', result.viewCount);
        console.log('Video Count:', result.videoCount);

        // Return both values
        return result;
    } catch (error) {
        console.error('Error:', error);

        // Output for script AND card
        await tag('subscriberCount', -1);
        await tag('videoCount', -1);
        await tag('viewCount', -1);

        // Return error values
        return {
            subscriberCount: -1,
            videoCount: -1,
            viewCount: -1
        };
    }
}

// Execute the main function
await main().then(result => {
    // You can access the final result here if needed
    console.log('Final Result:', result);
    if (result.subscriberCount === -1 || result.videoCount === -1 || result.viewCount === -1) {
        throw new Error('Execution failed');
    }
}).catch(error => {
    console.error('Final Error:', error);
    return false;
});

// Explicitly return true if no errors occurred
return true;


Glad that it was useful to somebody :slight_smile:

1 Like

I have just promised it to my daughter (she would like to see number of views and subscribers) :laughing:
So you saved me :wink:

Nice :heart:

Good job with the extension of it :slight_smile:

1 Like