# Youtube subscribers and/or views?

**URL:** <https://community.homey.app/t/youtube-subscribers-and-or-views/111912>\
**Category:** Apps\
**Tags:** homey-pro\
**Created:** [June 24, 2024, 6:26am UTC](https://community.homey.app/t/youtube-subscribers-and-or-views/111912 "2024-06-24T06:26:46Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![Sharkys](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/sharkys/32/54029_2.png) [@Sharkys](https://community.homey.app/u/Sharkys)\
**Post date:** [July 10, 2024, 10:00pm UTC](https://community.homey.app/t/youtube-subscribers-and-or-views/111912/3 "2024-07-10T22:00:46Z")

</div>

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

![script_result](https://us1.discourse-cdn.com/flex025/uploads/athom/original/3X/7/f/7f286b35a91dc8e4a78b058276f590a6087783ec.png)

```auto
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;

```

---

_[View the full topic](https://community.homey.app/t/youtube-subscribers-and-or-views/111912)._
