Pi Hole stats tweeter

Pi Hole stats tweeter

I wanted to send a a daily tweet with the results of what my Pi-Hole blocked.

How to use

Install following python dependencies with

sudo pip install tweepy datetime json urllib

Download python file and replace it with your own account data and link to your own path/to/admin/api.php. In my case it would be /var/www/html/admin.api.php or darthkeizer.ddns.net/admin.api.php

path/to/admin/api.php

/var/www/html/admin.api.php or

https://darthkeizer.ddns.net/admin.api.php

Script

#Send tweet when script is called

import tweepy
import datetime
import json
import urllib
from urllib.request import urlopen

# Retrieve data and load it into a dictionary
data = urlopen(‘path/to/admin/api.php’).read() #bytes
body = data.decode(‘utf-8’)
data = json.loads(body)

# Create tweet, adjust %.2f for amount of decimals you want or %i for a whole number
template_tweet = “\nAds Blocked: %s\nAds Percentage Today: %.2f\nDNS Queries Today: %s\nDomains Being Blocked: %s”
data = template_tweet % (data[‘ads_blocked_today’],
float (data[‘ads_percentage_today’]),
data[‘dns_queries_today’],
data[‘domains_being_blocked’]
)

def get_api(cfg):
auth = tweepy.OAuthHandler(cfg[‘consumer_key’], cfg[‘consumer_secret’])
auth.set_access_token(cfg[‘access_token’], cfg[‘access_token_secret’])
return tweepy.API(auth)

def main():
# Fill in the values noted in previous step here https://dev.twitter.com/oauth/overview/application-owner-access-tokens
cfg = {
“consumer_key” : “VALUE”,
“consumer_secret” : “VALUE”,
“access_token” : “VALUE”,
“access_token_secret” : “VALUE”
}

api = get_api(cfg)
tweet = datetime.datetime.today().strftime(“%Y-%m-%d”) + ” Daily Pi-Hole report\n ” + data
status = api.update_status(status=tweet)
# Yes, tweet is called ‘status’ rather confusing

if __name__ == “__main__”:
main()

Cronjob

This will tweet your stats at 23:59 everyday

59 23 * * * sudo python3 /path/to/twittertweeter.py >/dev/null 2>&1

Twitter acces keys and tokens

On their own website it is quite clearly explained: https://dev.twitter.com/oauth/overview/application-owner-access-tokens

Replace VALUE by the corrects keys, tokens and secrets.

Leave a Reply

Your email address will not be published. Required fields are marked *