radiobot/bot.py

58 lines
2.6 KiB
Python

import teambot, sys, tasks, json
import os.path as fs
class RadioBot(teambot.Handler):
def __init__(self,*args):
super(RadioBot,self).__init__(*args)
self.tasks = tasks.TaskPool(handler=self)
self.tasks.add_coroutine(self.check_nowplaying,1)
self.channels = [x.split()[0] for x in self._bot.chanlist]
self.tasks.run()
def check_nowplaying(self,state,basestate):
if not hasattr(self._bot,"conn"):
return {}
bot = basestate["handler"]
with open(fs.expanduser("~khuxkm/public_html/radiobot/now_playing.json")) as f:
resp = json.loads(f.read().rstrip())
if resp["dj"] is not None and not state.get("dj_live",False):
bot.say(bot.channels[0],"{} is now live!".format(resp["dj"]))
state["dj"] = resp["dj"]
state["dj_live"]=True
if resp["dj"] is None and state.get("dj_live",True):
state["dj_live"]=False
if resp["song"]!=state.get("song") or resp["listeners"]!=state.get("listeners"):
bot.say(bot.channels[0],"now playing: {} ({!s} listeners{})".format(resp["song"],resp["listeners"],(", played by "+resp["dj"] if resp["dj_live"] else "")))
state["song"]=resp["song"]
state["listeners"]=resp["listeners"]
basestate["handler"].task_state = state
return state
def on_pubmsg(self,channel,nick,text):
print(self.event.source.userhost)
if text.startswith(self._bot.bot_nick+": "):
cmd = text[len(self._bot.bot_nick+": "):].strip()
if self.event.source.userhost=="khuxkm@oper.tilde.chat" and cmd=="down":
self.tasks.stop()
self._bot.die("Stopping...")
elif cmd=="dj":
if self.task_state["dj_live"]:
self.say(channel,nick+": {} is the current dj!".format(self.task_state["dj"]))
else:
self.say(channel,nick+": nobody is live right now.")
elif cmd=="np":
self.say(channel,nick+": now playing: {} ({!s} listeners{})".format(self.task_state["song"],self.task_state["listeners"],(", played by "+self.task_state["dj"] if self.task_state["dj_live"] else "")))
elif cmd=="radio": # joke command
self.say(channel,"eat the poop or die!!1")
elif cmd=="paymybills": # joke command
self.say(channel,"whaddya mean?! i'm broker than you!")
elif text.strip()=="!botlist":
self.say(channel,"Maintainer: khuxkm@tilde.team | your friendly neighborhood radio bot | https://tildegit.org/khuxkm/radiobot")
if __name__=="__main__":
if not fs.exists("channels.txt"):
print("ERROR: No channels.txt. Use channels.txt.example as an example.")
sys.exit(1)
with open("channels.txt") as f:
channels = [l.rstrip() for l in f if l.rstrip()]
bot = teambot.TeamBot(channels,"radiobot2","localhost",chandler=RadioBot)
bot.start()