50 lines
1.3 KiB
Python
50 lines
1.3 KiB
Python
import time, requests, traceback, random
|
|
from bot import IRCLine
|
|
BOT = None
|
|
|
|
def time_secs():
|
|
return time.time()
|
|
|
|
USER_AGENT = "minerbot2 on tilde.chat IRC (ran by /u/kd2bwz2)"
|
|
|
|
def grab_posts():
|
|
r = requests.get("https://reddit.com/r/eyebleach/.json",headers={"User-Agent":USER_AGENT})
|
|
if r.status_code==200: return [x["data"] for x in r.json()["data"]["children"]]
|
|
try:
|
|
r.raise_for_status()
|
|
except: traceback.print_exc() # print status code error
|
|
return [] # return empty list
|
|
|
|
LAST_GRAB = time_secs()
|
|
_posts = grab_posts()
|
|
|
|
def posts():
|
|
global LAST_GRAB,_posts
|
|
if (time_secs()-LAST_GRAB)>=(5*60): # cache for 5 minutes
|
|
LAST_GRAB = time_secs()
|
|
_posts = grab_posts()
|
|
return _posts
|
|
|
|
def respond(event,msg):
|
|
target = event.target if event.target.startswith("#") else event.hostmask.nick
|
|
prefix = ""
|
|
if event.target.startswith("#"): prefix=event.hostmask.nick+": "
|
|
BOT.socket.send(IRCLine("PRIVMSG",target,":"+prefix+msg))
|
|
|
|
RNG = random.SystemRandom()
|
|
|
|
def on_cheerup(event):
|
|
if not BOT: return
|
|
try:
|
|
post = RNG.choice(posts())
|
|
respond(event,f"{post['title']} - {post['url']}")
|
|
except:
|
|
traceback.print_exc()
|
|
respond(event,"Something went wrong!")
|
|
|
|
def register(bot):
|
|
global BOT
|
|
BOT=bot
|
|
bot.event_manager.on("command_cheerup",on_cheerup)
|
|
bot.event_manager.on("command_cute",on_cheerup)
|