YouTube channel subscription and views count to Pushover

I’ve made a new script similar to Facebook page like count to Pushover that keeps track of my YouTube stats.

It’s no secret that I love statistics and notifications. Even though my YouTube account doesn’t get a lot of views or new subscribers, I wanted to get notified whenever there’s a major change. The script uses Pushover to send notifications if a new user subscribes to your channel or whenever your total number of views increases by a given threshold (100 views by default).

This post is now outdated and unsupported. Get the latest code here.
#!/usr/bin/python

import sys
import re
from lxml import etree
import urllib2, os, httplib, urllib

PUSHOVER_USER = "xxxxxxxxxxxxxxx"
YOUTUBE_URLS = [["IDmedia", "ChannelID","PushoverApiKey"]]
YOUTUBE_VIEWS_DIFF = 100

def main():
 # Change to our directory
 abspath = os.path.abspath(__file__)
 dname = os.path.dirname(abspath)
 os.chdir(dname)

 for yturl in YOUTUBE_URLS:
 # Setup variables
 name = "".join([c for c in yturl[0] if c.isalpha() or c.isdigit() or c==' ']).rstrip()
 channel_id = yturl[1]
 subscriber_filename = 'subscriber_count_%s.txt' % name.lower()
 views_filename = 'views_count_%s.txt' % name.lower()

 # Verify that the subscriber and views txt file exists
 if not os.path.isfile(subscriber_filename) or not os.path.isfile(views_filename):
 createfile('subscribers', subscriber_filename, channel_id)
 createfile('views', views_filename, channel_id)

 # Collect subscriber and views count
 youtube_data = readyoutubedata(channel_id)
 
 previous_subscriber_count = int(readfile(subscriber_filename))
 new_subscriber_count = int(youtube_data['subscribers'])
 diff_subscriber_count = new_subscriber_count - previous_subscriber_count

 previous_views_count = int(readfile(views_filename))
 new_views_count = int(youtube_data['views'])
 diff_views_count = new_views_count - previous_views_count

 if diff_subscriber_count != 0:
 # The number of subscribers has changed, send notification and update subscriber txt
 createnotification(name, 'Subscribers', yturl[2], new_subscriber_count, diff_subscriber_count)
 createfile('subscribers', subscriber_filename, channel_id)

 if diff_views_count >= YOUTUBE_VIEWS_DIFF:
 # The number of views has changed significantly, send notification and update views txt
 createnotification(name, 'Views', yturl[2], '{0:,}'.format(new_views_count), diff_views_count)
 createfile('views', views_filename, channel_id)


def readyoutubedata(channel_id):
 headers = { 'User-Agent' : 'Mozilla/5.0' }
 req = urllib2.Request("https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20where%20url%3D%22https%3A%2F%2Fwww.youtube.com%2Fchannel%2F" + channel_id + "%2Fabout%22%20%0AAND%20xpath%3D'%2F%2F*%5B%40class%3D%22about-stats%22%5D%2F%2Fb'&format=xml", None, headers)

 youtube_data = urllib2.urlopen(req).read()
 youtube = etree.fromstring(youtube_data)
 result = {'subscribers': youtube.find('.//results/b[1]').text, 'views': re.sub("[^0-9]", "", youtube.find('.//results/b[2]').text)}

 return result

def createfile(stats, filename, channel_id):
 youtube_data = readyoutubedata(channel_id)

 if youtube_data:
 with open(filename, "w") as text_file:
 text_file.write(youtube_data[str(stats)])

def readfile(filename):
 with open (filename, "r") as text_file:
 return text_file.read().replace('\n', '')

def createnotification(name, type, pushover_token, new_count, diff_count):
 conn = httplib.HTTPSConnection("api.pushover.net:443")
 conn.request("POST", "/1/messages.json",
 urllib.urlencode({
 "token": pushover_token,
 "user": PUSHOVER_USER,
 "message": "%s for %s: %s\nChange since last update: %s" % (type, name, new_count, diff_count),
 }), { "Content-type": "application/x-www-form-urlencoded" })
 conn.getresponse()

if __name__ == '__main__':
 main()
Share this:

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.