#!/usr/bin/env python import json import os import requests as r import secret from time import time import traceback API_CALL = 'https://suya.place/api/v1/statuses' API_HEADERS = { 'Authorization': 'Bearer %s' % (secret.TOKEN) } # API key here! EXCEPTION_MESSAGE_FORMAT = '@a1ba\n%s' # send an exception text to my direct messages KOTCRAB_API = 'https://kotcrab.com/progress/proxy/ccc?x=%d' def get_stats(): data = r.get(KOTCRAB_API % int(time() * 1000)).json() return data[0]['units'], data[1]['units'] def post(visibility, status): resp = r.post(API_CALL, headers = API_HEADERS, json = { 'visibility': visibility, 'status' : status }) return resp.status_code == 200 def parse_stats(stats, ref): data = {} # this stuff isn't documented by Kotcrab so let's be careful here if stats.keys() != ref.keys(): raise Exception for k in stats.keys(): if ref[k]['name'] != stats[k]['name']: raise Exception all_pages = len(ref[k]['data']) edited_pages = int(float(stats[k]['edited']) * 0.01 * all_pages) data[stats[k]['name']] = { 'edited': edited_pages, 'all': all_pages } return data def dump_and_compare_data(new): s = json.dumps(new, indent = '\t') with open('last.json.new', 'w') as fd: fd.write(s) try: with open('last.json', 'r') as fd: s = fd.read() old = json.loads(s) for k in new: if k not in old: new[k]['update'] = True continue new[k]['update'] = old[k] != new[k] except OSError: for k in new: new[k]['update'] = False os.rename('last.json.new', 'last.json') def compose_text(data): text = 'Today\'s CCC Editing Progress: \n' for k in data: d = data[k] mark = '' if d['update']: if d['edited'] == d['all']: mark = '🎉' # my font can't render this emoji lul else: mark = '⚠️' percent = d['edited'] / float(d['all']) * 100.0 text += '%s: %.2f%% (%d/%d) %s\n' % (k, percent, d['edited'], d['all'], mark) return text def main(): stats, ref = get_stats() stats = parse_stats(stats, ref) dump_and_compare_data(stats) text = compose_text(stats) print(text) # bots are forced to be unlisted on my instance anyway post('unlisted', text) if __name__ == "__main__": try: main() except Exception as e: t = traceback.format_exc() print(t) post('direct', EXCEPTION_MESSAGE_FORMAT % t)