# 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:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Fredrik\_Tornell](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/fredrik_tornell/32/48574_2.png) [@Fredrik\_Tornell](https://community.homey.app/u/Fredrik_Tornell)\
**Post date:** [June 24, 2024, 6:26am UTC](https://community.homey.app/t/youtube-subscribers-and-or-views/111912/1 "2024-06-24T06:26:46Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Daxziz](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/daxziz/32/43405_2.png) [@Daxziz](https://community.homey.app/u/Daxziz)\
**Post date:** [July 8, 2024, 7:38am UTC](https://community.homey.app/t/youtube-subscribers-and-or-views/111912/2 "2024-07-08T07:38:49Z")

</div>

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](https://console.cloud.google.com/cloud-resource-manager).
- 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:

```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 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);
});

```

---

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

```

---

<div class="post-metadata">

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

</div>

Glad that it was useful to somebody 🙂

---

<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:25pm UTC](https://community.homey.app/t/youtube-subscribers-and-or-views/111912/5 "2024-07-10T22:25:28Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Daxziz](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/daxziz/32/43405_2.png) [@Daxziz](https://community.homey.app/u/Daxziz)\
**Post date:** [July 11, 2024, 7:53am UTC](https://community.homey.app/t/youtube-subscribers-and-or-views/111912/6 "2024-07-11T07:53:41Z")

</div>

Nice ❤

Good job with the extension of it 🙂

---

<div class="post-metadata">

**Author:** ![Domotica-blog.nl](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/domotica-blog.nl/32/69291_2.png) [@Domotica-blog.nl](https://community.homey.app/u/Domotica-blog.nl)\
**Post date:** [December 8, 2024, 10:48am UTC](https://community.homey.app/t/youtube-subscribers-and-or-views/111912/7 "2024-12-08T10:48:44Z")

</div>

Thank u for this script…works great!
