68 lines
1.6 KiB
Python
68 lines
1.6 KiB
Python
|
import plugin, time, requests
|
||
|
from jsonpath import jsonpath
|
||
|
from pluralslib import plural
|
||
|
from bot import IRCLine
|
||
|
BOT = None
|
||
|
|
||
|
def say(target,msg):
|
||
|
if not BOT: return None
|
||
|
BOT.socket.send(IRCLine("PRIVMSG",target,":"+msg))
|
||
|
|
||
|
def query(jpath,reducer=lambda x: x[0]):
|
||
|
def _query(stats):
|
||
|
return reducer(jsonpath(stats,jpath))
|
||
|
return _query
|
||
|
|
||
|
QUERIES = dict(
|
||
|
users = query("$.usercount"),
|
||
|
channels = query("$.channelcount")
|
||
|
)
|
||
|
|
||
|
NOUNS = dict(
|
||
|
users="user",
|
||
|
channels="channel"
|
||
|
)
|
||
|
|
||
|
def time_secs():
|
||
|
return time.time()
|
||
|
|
||
|
def grab_stats():
|
||
|
r = requests.get("https://tilde.chat/stats.json")
|
||
|
r.raise_for_status()
|
||
|
return r.json()
|
||
|
|
||
|
LAST_GRAB = time_secs()
|
||
|
_stats = grab_stats()
|
||
|
|
||
|
def stats():
|
||
|
global LAST_GRAB,_stats
|
||
|
if (time_secs()-LAST_GRAB)>=(5*60): # cache for 5 minutes
|
||
|
LAST_GRAB = time_secs()
|
||
|
_stats = grab_stats()
|
||
|
return _stats
|
||
|
|
||
|
USAGE_STR = "<{}>".format("/".join(QUERIES.keys()))
|
||
|
|
||
|
def stat(bot,channel,nick,subcmd):
|
||
|
if subcmd not in QUERIES.keys():
|
||
|
say(channel,("{}: ".format(nick) if channel.startswith("#") else " ".strip())+"Usage: !stats {}".format(USAGE_STR))
|
||
|
return
|
||
|
st = stats()
|
||
|
res = plural(QUERIES.get(subcmd,lambda x: 0)(st),NOUNS.get(subcmd,"fuck"))
|
||
|
say(channel,": ".join(([nick] if channel.startswith("#") else [])+[res]))
|
||
|
|
||
|
def on_stats(event):
|
||
|
if not BOT: return None
|
||
|
channel = event.target if event.target.startswith("#") else event.hostmask.nick
|
||
|
try:
|
||
|
stat(BOT,channel,event.hostmask.nick,*event.parts)
|
||
|
except TypeError:
|
||
|
say(channel,"Usage: !stats <{}>".format("/".join(QUERIES.keys())))
|
||
|
except Exception as e:
|
||
|
traceback.print_exc()
|
||
|
|
||
|
def register(bot):
|
||
|
global BOT
|
||
|
BOT=bot
|
||
|
bot.event_manager.on("command_stats",on_stats)
|