Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import faulthandler
- faulthandler.enable()
- import irc.bot
- import irc.strings
- from django.utils.html import escape
- import sqlite3
- import json
- try:
- import urllib.request as urllib2
- except:
- import urllib2
- import datetime
- import threading
- import time
- from time import gmtime, strftime
- import logging
- import sys
- import codecs
- import random
- import re
- from collections import deque
- killbot = False
- FORMAT="[%(levelname)s] %(asctime)s - %(message)s"
- LOGDIR = "/home/django/django_project/logs/"
- #logging.basicConfig(filename=LOGDIR+"logviewer_%s.log"%(time.strftime("%Y_%m_%d_%H_%M_%S")),level=logging.INFO,format=FORMAT)
- handler = logging.FileHandler(LOGDIR+"slashbot_%s.log"%(time.strftime("%Y_%m_%d"),),"a",encoding = "UTF-8")
- formatter = logging.Formatter(FORMAT)
- handler.setFormatter(formatter)
- root_logger = logging.getLogger()
- root_logger.addHandler(handler)
- root_logger.setLevel(logging.INFO)
- #if sys.stdout.encoding != 'cp850':
- # sys.stdout = codecs.getwriter('cp850')(sys.stdout.buffer, 'strict')
- #if sys.stderr.encoding != 'cp850':
- # sys.stderr = codecs.getwriter('cp850')(sys.stderr.buffer, 'strict')
- if sys.stdout.encoding != 'cp850':
- sys.stdout = codecs.getwriter('cp850')(sys.stdout, 'strict')
- if sys.stderr.encoding != 'cp850':
- sys.stderr = codecs.getwriter('cp850')(sys.stderr, 'strict')
- class SQLRequest:
- def __init__(self, sql, data=[], hasdata=False):
- self.sql = sql
- self.res = []
- self.data = data
- self.done = False
- self.hasdata = hasdata
- self.rowid = None
- def __str__(self):
- return ('{"sql":"%s","res":"%s","data":"%s","done":%s}'%(self.sql,self.res,self.data,self.done)).encode("utf-8").decode("ascii", errors='replace')
- class SQLiteDriver:
- def __init__(self, dbloc):
- self.queue = deque()
- self.writequeue = deque()
- root_logger.info("Starting database driver")
- self.dbloc = dbloc
- self.lastrow = 0
- self.lastflush = time.time()
- threading.Thread(target=self.run).start()
- def execute(self, sql, data, wait):
- myreq = SQLRequest(sql,data)
- myreq.hasdata = sql.startswith("SELECT")
- cnt = 0
- if wait:
- self.queue.append(myreq)
- while(cnt < 1000):
- if(myreq.done):
- print("Returning query result: %s"%(myreq,))
- self.lastrow = myreq.rowid
- return myreq.res
- else:
- cnt += 1
- time.sleep(0.01)
- root_logger.error("Request timeout: %s"%(myreq,))
- else:
- self.writequeue.append(myreq)
- if(len(self.writequeue)>10 or (time.time()-self.lastflush)>1):
- self.flushWrite()
- try:
- print("Adding query %s to writequeue"%(req,))
- except Exception:
- pass
- return ""
- def run(self):
- self.dbconn = sqlite3.connect(self.dbloc,timeout=10)
- c = self.dbconn.cursor()
- while(1):
- try:
- c.execute("begin")
- didsth = False
- while self.queue:
- didsth = True
- cnt = 0
- req = self.queue.popleft()
- root_logger.debug("Executing query: %s"%(req,))
- le = 0
- while(cnt<10 and cnt>=0):
- try:
- r = c.execute(req.sql,req.data)
- if(req.hasdata):
- req.res = r.fetchall()
- req.rowid = r.lastrowid
- req.done = True
- cnt = -1
- break
- except Exception as e:
- cnt += 1
- time.sleep(0.01)
- le = e
- root_logger.exception(e)
- root_logger.error(req.sql)
- root_logger.error(req.data)
- pass
- if(cnt>=10):
- print("QUEUE ERROR")
- if not didsth:
- time.sleep(0.01)
- self.dbconn.commit()
- except Exception as e:
- root_logger.exception(e)
- print(e)
- try:
- c.execute("rollback")
- except Exception:
- pass
- pass
- def flushWrite(self):
- print("FLUSHING QUEUE")
- self.queue.extend(self.writequeue)
- self.writequeue = deque()
- self.lastflush = time.time()
- class TwitchChannel:
- def __init__(self, ch, sv):
- self.channel = "#"+ch
- self.twitchch = ch
- self.twitchsv = sv
- self.active = True
- self.specialusers = []
- self.subscribers = []
- self.lastchallenge = dict()
- self.challenger = dict()
- self.updateSpecialusers()
- self.ops = []
- def getRepr(self):
- return {"name":self.twitchch,"server":self.twitchsv,"active":self.active}
- def updateSpecialusers(self):
- try:
- res = pointdb.execute("SELECT User,Level FROM points_%s WHERE Level>0"%(self.twitchch,),[],True)
- self.specialusers = dict()
- for row in res:
- self.specialusers[row[0]] = int(row[1])
- except Exception as e:
- root_logger.exception(e)
- def getUserLevel(self,user):
- x = 0
- if user in self.specialusers:
- x = self.specialusers[user]
- if user in self.subscribers:
- x = max(x,2)
- if user in self.ops:
- x = max(x,5)
- return x
- class TwitchBot(irc.bot.SingleServerIRCBot):
- def __init__(self, server, servername, port=6667):
- irc.bot.SingleServerIRCBot.__init__(self, [(server, port,"oauth:dbjkzu3xne12ug2ml7t0ugsk4ubxkai")], "InternetPoinz", "InternetPoinz")
- try:
- self.twitchsv = servername
- self.twitchchs = dict()
- self.welcomed = False
- root_logger.info("Bot for "+self.twitchsv+" created.")
- self.sendqueue = deque()
- self.cc = None
- print("Bot for "+self.twitchsv+" created.")
- threading.Thread(target=self.sendAgent).start()
- except Exception as e:
- root_logger.exception(e)
- def joinChannel(self,chanU):
- chan = chanU.lower()
- self.ensureTableExists(chan)
- changedsince[chan] = False
- ch = TwitchChannel(chan,self.twitchsv)
- root_logger.info("Joining channel "+chan)
- if(self.welcomed):
- self.connection.join(ch.channel)
- print("Channel "+chan+" joined")
- root_logger.info("Channel "+chan+" joined")
- self.twitchchs[chan] = ch
- def leaveChannel(self,chan):
- if(chan in self.twitchchs.keys()):
- if(self.welcomed):
- print("Leaving channel "+chan)
- root_logger.info("Leaving channel "+chan)
- self.connection.part(self.twitchchs[chan].channel)
- self.twitchchs.__delitem__(chan)
- def on_welcome(self, c, e):
- c.send_raw("twitchclient 3")
- root_logger.info("Connected to server "+self.twitchsv)
- print("Connected to server "+self.twitchsv)
- for ch in self.twitchchs:
- self.connection.join(self.twitchchs[ch].channel)
- print("On welcome: Channel "+ch+" joined.")
- root_logger.info("On welcome: Channel "+ch+" joined.")
- self.welcomed = True
- def on_pubmsg(self, c, e):
- self.cc = c
- self.addLine(e.target.replace("#",""),e.source.nick, e.arguments[0])
- def on_privmsg(self, c, e):
- self.cc = c
- self.addLine(e.target.replace("#",""),e.source.nick, e.arguments[0])
- def on_ctcp(self, c, e):
- self.cc = c
- self.addLine(e.target.replace("#",""),e.source.nick, e.arguments[1])
- def on_mode(self, c, e):
- chan = ""
- try:
- chan = self.twitchchs[e.target.replace("#","")]
- except:
- return
- pass
- if len(e.arguments)==2:
- if e.arguments[0]=="+o":
- if e.arguments[1] not in chan.ops:
- chan.ops.append(e.arguments[1])
- print("added %s as op"%e.arguments[1])
- elif e.arguments[0]=="-o":
- if e.arguments[1] in chan.ops:
- chan.ops.remove(e.arguments[1])
- print("removed %s as op"%e.arguments[1])
- def sendAgent(self):
- while(1):
- try:
- if len(self.sendqueue) > 0:
- x = self.sendqueue.popleft()
- self.cc.privmsg("#"+x[0],x[1])
- print("--> #"+x[0]+": "+x[1])
- time.sleep(2)
- else:
- time.sleep(1)
- except Exception as e:
- root_logger.exception(e)
- pass
- def sendLine(self,ch,text):
- self.sendqueue.append((ch,text))
- def addLine(self, channel, nick, text):
- try:
- print(nick+": "+text)
- except:
- pass
- chan = ""
- try:
- chan = self.twitchchs[channel]
- except:
- return
- pass
- try:
- if nick=="jtv":
- ex = text.split(" ",2)
- for i in range(len(ex)):
- ex[i] = ex[i].strip().lower()
- if ex[0] == "specialuser":
- if ex[2] == "subscriber" and ex[1] not in chan.subscribers:
- chan.subscribers.append(ex[1])
- print("Added %s as subscriber"%(ex[1]))
- if text.startswith("!"):
- lv = chan.getUserLevel(nick)
- ex = text.split(" ",1)
- ex2 = []
- ex2.extend(ex)
- if len(ex)>0:
- for i in range(len(ex)):
- ex[i] = ex[i].strip().lower()
- if lv>=chan.getUserLevel(ex[0]):
- if ex[0] == "!level":
- if len(ex)==2:
- d = ex[1].split()
- if len(d)==1:
- self.sendLine(channel,"Userlevel of %s is %s"%(d[0],chan.getUserLevel(d[0])))
- elif len(d)==2:
- try:
- nlv = int(d[1])
- if nlv<lv and chan.getUserLevel(d[0])<lv:
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(channel,),[d[0],nlv],True)
- pointdb.execute(("UPDATE OR IGNORE points_%s SET Level=(?) WHERE User=(?)")%(channel,),[nlv,d[0]],True)
- self.sendLine(channel,"Set userlevel of %s from %s to %s"%(d[0],chan.getUserLevel(d[0]),nlv))
- chan.updateSpecialusers()
- else:
- self.sendLine(channel,"Cannot set userlevel of %s: Access denied."%(d[0],))
- except Exception as e:
- self.sendLine(channel,"Userlevel %s invalid"%(d[1]))
- root_logger.exception(e)
- pass
- if ex[0] == "!removeme":
- pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(channel),),(nick,-9999999),False)
- pointdb.execute("UPDATE points_%s SET Points=-99999999 WHERE User=?"%getTableUser(channel),(nick,),False)
- changedsince[channel] = True
- self.sendLine(channel,"Removed user %s from the points bot."%(nick,))
- if ex[0] == "!remove":
- if len(ex)==2:
- pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(channel),),(ex[1].lower(),-9999999),False)
- pointdb.execute("UPDATE points_%s SET Points=-99999999 WHERE User=?"%getTableUser(channel),(ex[1].lower(),),False)
- changedsince[channel] = True
- self.sendLine(channel,"Removed user %s from the points bot."%(ex[1],))
- if ex[0] == "!give":
- if len(ex)==2:
- d = ex[1].strip().split(" ",1)
- if len(d)==2:
- try:
- ps = int(d[1])
- usr = d[0].lower().strip()
- if usr=="everyone":
- pointdb.execute("UPDATE OR IGNORE points_%s SET Points=Points+(?) WHERE Points>0 AND User NOT LIKE '!%%'"%getTableUser(channel),(d[1],),False)
- changedsince[channel] = True
- self.sendLine(channel,"Gave everyone %s points."%(d[1],))
- elif usr=="chatters":
- give_chatters(channel,d[1])
- changedsince[channel] = True
- self.sendLine(channel,"Gave everyone currently in chat %s points."%(d[1],))
- else:
- pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(channel),),(usr,0),False)
- pointdb.execute("UPDATE OR IGNORE points_%s SET Points=Points+(?) WHERE User=(?)"%getTableUser(channel),(d[1],usr,),False)
- changedsince[channel] = True
- if usr.startswith("!"):
- self.sendLine(channel,"Increased point setting on command %s by %s points."%(usr,d[1]))
- else:
- self.sendLine(channel,"Gave user %s %s points."%(usr,d[1]))
- except Exception as e:
- print("Error in !give: "+str(e))
- pass
- pointdb.flushWrite()
- if ex[0] == "!boost":
- if len(ex)==2:
- d = ex[1].strip().split(" ",1)
- try:
- duration = int(d[0]) # in 10 minute ticks
- powah = ""
- if len(d)==2:
- try:
- power = int(d[1])
- pointdb.execute("UPDATE OR IGNORE points_%s SET Points=(?) WHERE User=(?)"%getTableUser(channel),(d[1],"!boost-power",),False)
- powah = " with boost power %d"%(power,)
- except Exception as e:
- root_logger.exception(e)
- print(e)
- pass
- pointdb.execute("UPDATE OR IGNORE points_%s SET Points=(?) WHERE User=(?)"%getTableUser(channel),(d[0],"!boost",),False)
- if duration>0:
- hrs = int(duration/6)
- mins = (duration%6)*10
- dstr = ""
- if(hrs>0):
- dstr = " %d hour"%(hrs,)
- if(mins>0):
- dstr += " %d minute"%(mins,)
- self.sendLine(channel,"Set%s boost on channel %s%s."%(dstr,channel,powah))
- else:
- self.sendLine(channel,"Removed boost on channel %s."%(channel,))
- pointdb.flushWrite()
- except Exception as e:
- root_logger.exception(e)
- print(e)
- pass
- else:
- pts = 1
- try:
- res = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),("!boost",),True)
- for row in res:
- duration = int(row[0]) # in 10 minute ticks
- if(duration>0):
- if duration>0:
- hrs = int(duration/6)
- mins = (duration%6)*10
- dstr = ""
- if(hrs>0):
- dstr = " %d hours"%(hrs,)
- if(mins>0):
- dstr += " %d minutes"%(mins,)
- res2 = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),("!boost-power",),True)
- for row2 in res2:
- pts = int(row2[0])
- self.sendLine(channel,"Channel %s is boosted for%s with boost power %d."%(channel,dstr,pts))
- break
- else:
- self.sendLine(channel,"Channel %s is not boosted."%(channel,))
- except Exception as e:
- root_logger.exception(e)
- print(e)
- pass
- pointdb.flushWrite()
- if ex[0] == "!set":
- if len(ex)==2:
- d = ex[1].strip().split(" ",1)
- if len(d)==2:
- try:
- ps = int(d[1])
- usr = d[0].lower().strip()
- if usr=="everyone":
- pointdb.execute("UPDATE OR IGNORE points_%s SET Points=(?) WHERE Points>0 AND User NOT LIKE '!%'"%getTableUser(channel),(d[1],),False)
- self.sendLine(channel,"Set everyones points to %s."%(d[1],))
- changedsince[channel] = True
- elif usr=="chatters":
- set_chatters(channel,d[1])
- self.sendLine(channel,"Set the points of everyone currently in chat to %s."%(d[1],))
- changedsince[channel] = True
- else:
- pointdb.execute("UPDATE OR IGNORE points_%s SET Points=(?) WHERE User=(?)"%getTableUser(channel),(d[1],usr),False)
- if usr.startswith("!"):
- self.sendLine(channel,"Set the point setting on command %s to %s points."%(usr,d[1]))
- else:
- self.sendLine(channel,"Set the points of user %s to %s."%(usr,d[1]))
- changedsince[channel] = True
- except:
- pass
- pointdb.flushWrite()
- if ex[0] == "!points":
- if len(ex)==2:
- try:
- res = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),(ex[1],),True)
- for row in res:
- p=0
- try:
- p = int(row[0])
- except Exception:
- pass
- if p>=0:
- if ex[1].startswith("!"):
- self.sendLine(channel,"Points setting on command %s is %s."%(ex[1],row[0]))
- else:
- self.sendLine(channel,"User %s has %s points."%(ex[1],row[0]))
- else:
- if ex[1].startswith("!"):
- self.sendLine(channel,"Point cap for %s has been disabled."%(ex[1],))
- else:
- self.sendLine(channel,"User %s has been removed from the leaderboards."%(ex[1],))
- except:
- pass
- elif len(ex)==1:
- try:
- res = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),(nick,),True)
- for row in res:
- p=0
- try:
- p = int(row[0])
- except Exception:
- pass
- if p>=0:
- self.sendLine(channel,"User %s has %s points."%(nick,row[0]))
- else:
- self.sendLine(channel,"User %s has been removed from the leaderboards."%(nick,))
- except:
- pass
- if ex[0] == "!forceupdate":
- pointdb.flushWrite()
- time.sleep(1)
- cc = channel
- if len(ex)==2:
- cc = ex[1]
- ccc = getTableUser(cc)
- threading.Thread(target=open_website, args=[baseurl+"/api/updatepoints/"+getTableUser(ccc)]).start()
- changedsince[channel] = False
- if(ccc==cc):
- self.sendLine(channel,"Forcibly updated points leaderboard for channel %s."%(ccc,))
- else:
- self.sendLine(channel,"Forcibly updated points leaderboard for linked channel %s."%(ccc,))
- if ex[0] == "!help":
- self.sendLine(channel,"Help and command list: slashcaststd.com/slashbot/lv/help/")
- if ex[0] == "!leaderboard":
- self.sendLine(channel,"Slash Generals leaderboard: slashcaststd.com/slashbot/leaderboard")
- if ex[0] == "!army":
- self.sendLine(channel,"Manage your minions at slashcaststd.com/slashbot/")
- if ex[0] == "!challenge":
- if len(ex)==2:
- lt = datetime(1970,1,1)
- if(nick in chan.lastchallenge):
- lt = chan.lastchallenge[nick]
- dt = (datetime.datetime.now - lt).total_seconds()
- if dt>=180:
- lt = datetime(1970,1,1)
- if(ex[1] in chan.lastchallenge):
- lt = chan.lastchallenge[ex[1]]
- dt = (datetime.datetime.now - lt).total_seconds()
- if dt < 180:
- self.sendLine(channel,"User %s has a challenge running. In %d minutes, the challenge will run out."%(ex[1],int(dt/60)))
- else:
- chan.lastchallenge[nick] = datetime.datetime.now
- chan.lastchallenge[ex[1]] = datetime.datetime.now
- chan.challenger[ex[1]] = nick
- self.sendLine(channel,"User %s has challenged %s to a duel! %s, type !accept to accept the duel request!"%(ex[1],int(dt/60)))
- if ex[0] == "!accept":
- if nick in chan.challenger:
- p = [chan.challenger[nick],nick]
- # grab data
- res = pointdb.execute("SELECT User,Army,ArmySize FROM points_%s WHERE User=(?) OR User=(?)"%(channel,),(p[0],p[1]))
- if ex[0] == "!test":
- if len(ex) == 1:
- self.sendLine(channel,"Test reply to "+nick+" sent at "+strftime("%a, %d %b %Y %H:%M:%S UTC", gmtime()))
- else:
- self.sendLine(channel,"Test reply to %s sent at %s (%s)"%(nick,strftime("%a, %d %b %Y %H:%M:%S UTC", gmtime()),ex[1]))
- except Exception as e:
- root_logger.exception(e)
- try:
- print(e)
- except:
- pass
- pass
- def ensureTableExists(self, ch):
- print("Creating tables for "+getTableUser(ch))
- pointdb.execute(("CREATE TABLE IF NOT EXISTS [points_%s] ("
- "[User] TEXT PRIMARY KEY NOT NULL,"
- "[Points] INTEGER DEFAULT '0' NOT NULL,"
- "[TotalPoints] INTEGER DEFAULT '0' NOT NULL,"
- "[Level] INTEGER DEFAULT '0' NOT NULL,"
- "[Army] TEXT DEFAULT (?) NOT NULL,"
- "[ArmySize] INTEGER DEFAULT '0' NOT NULL,"
- "[Oauth] TEXT DEFAULT '' NOT NULL"
- ")")%(ch,),['[0,0,0,0]',],True)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),[ch,10],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["cbenni",1337],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!give",9],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!set",9],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!remove",9],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!forceupdate",9],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!level",5],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!test",5],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!points",1],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!leaderboard",1],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!army",1],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!help",1],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!challenge",0],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!accept",0],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!decline",0],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!removeme",0],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level,Points) VALUES (?,?,?)")%(ch,),["!boost",9,0],False)
- pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level,Points) VALUES (?,?,?)")%(ch,),["!boost-power",999,2],False)
- pointdb.execute(("CREATE INDEX IF NOT EXISTS armyindex_%s ON points_%s (ArmySize DESC)")%(ch,ch),[],False)
- pointdb.flushWrite()
- print("Done creating table for "+ch)
- def getTableUser(usr):
- return usr
- def open_website(url):
- root_logger.debug(urllib2.urlopen(url))
- def give_chatters(cc,pts):
- try:
- res = urllib2.urlopen("http://tmi.twitch.tv/group/user/%s/chatters"%cc)
- data = res.read().decode("utf-8")
- chatterdata = json.loads(data)
- cats = ["moderators","staff","admins","viewers"]
- for cat in cats:
- for v in chatterdata["chatters"][cat]:
- pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(cc),),(v,0),False)
- pointdb.execute("UPDATE points_%s SET Points=Points+(?) WHERE User=(?)"%getTableUser(cc),(pts,v),False)
- changedsince[cc] = True
- except Exception as e:
- root_logger.exception(e)
- print("error: "+str(e))
- pass
- def set_chatters(cc,pts):
- try:
- res = urllib2.urlopen("http://tmi.twitch.tv/group/user/%s/chatters"%cc)
- data = res.read().decode("utf-8")
- chatterdata = json.loads(data)
- cats = ["moderators","staff","admins","viewers"]
- for cat in cats:
- for v in chatterdata["chatters"][cat]:
- pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(cc),),(v,0),False)
- pointdb.execute("UPDATE points_%s SET Points=(?) WHERE User=(?)"%getTableUser(cc),(pts,v),False)
- changedsince[cc] = True
- except Exception as e:
- root_logger.exception(e)
- print("error: "+str(e))
- pass
- def getPointsPerTick(channel,islive):
- pts = 1
- if islive:
- pts = 25
- try:
- res = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),("!boost",),True)
- for row in res:
- if(int(row[0])>0):
- res2 = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),("!boost-power",),True)
- for row2 in res2:
- pts = int(row2[0])
- pointdb.execute("UPDATE OR IGNORE points_%s SET Points=Points-1 WHERE User=(?)"%getTableUser(channel),("!boost",),False)
- print("Channel %s is boosted with power %d"%(channel,pts))
- break
- except Exception as e:
- root_logger.exception(e)
- print(e)
- pass
- pointdb.flushWrite()
- return pts
- def updateLoop():
- global kappalist
- global coincounter
- try:
- root_logger.debug("Starting update loop.")
- # get coinchannels
- res = urllib2.urlopen(baseurl+"/api/channels")
- data = res.read().decode("utf-8")
- chdata = json.loads(data)
- tmpchdata = []
- # kill removed/changed bots
- # tmpchdata contains those bots that survive
- # additionally, we update the specialusers
- for svr in servers:
- sv = servers[svr]
- for ch in sv.twitchchs:
- cd = sv.twitchchs[ch].getRepr()
- if cd in chdata:
- tmpchdata.append(cd)
- else:
- root_logger.info("Killing bot "+str(cd))
- sv.leaveChannel(ch)
- for cd in chdata:
- if(cd not in tmpchdata and cd["active"]==True):
- root_logger.info("Deploying bot "+str(cd))
- servers[cd["server"]].joinChannel(cd["name"])
- # now we collect some data...
- chstring = ""
- livechans = []
- firstch = True
- try:
- res = urllib2.urlopen("http://api.justin.tv/api/stream/list.json?channel="+",".join(coindata))
- data = res.read().decode("utf-8")
- streamdata = json.loads(data)
- for stream in streamdata:
- livechans.append(stream["channel"]["title"])
- except Exception as e:
- print("Exception when trying to get live streams")
- print(e)
- root_logger.exception(e)
- pass
- coincounter = coincounter+1
- chcounter=0
- try:
- print(changedsince)
- except:
- pass
- try:
- for coinchan in coindata:
- cc = coinchan.lower()
- if (coincounter+chcounter)%60==2:
- pts = getPointsPerTick(cc,coinchan in livechans)
- give_chatters(cc,pts)
- if (coincounter+chcounter)%60==32 and coinchan in livechans:
- pts = getPointsPerTick(cc,True)
- give_chatters(cc,pts)
- if (coincounter+chcounter)%10==3:
- if(changedsince[cc] == True):
- print("Updating points for "+coinchan)
- threading.Thread(target=open_website, args=[baseurl+"/api/updatepoints/"+cc]).start()
- changedsince[cc] = False
- else:
- print("Not updating points for "+coinchan)
- chcounter = chcounter+1
- except Exception as e:
- root_logger.exception(e)
- print(e)
- pass
- pointdb.flushWrite()
- except Exception as e:
- root_logger.exception(e)
- pass
- baseurl = "http://127.0.0.1/slashminion"
- res = urllib2.urlopen(baseurl+"/api/databases")
- data = res.read().decode("utf-8")
- info = json.loads(data)
- servers = {}
- coincounter = 0
- changedsince = dict()
- if(info):
- pointdbloc = info["points"]["url"]
- pointdb = SQLiteDriver(pointdbloc)
- res = urllib2.urlopen(baseurl+"/api/servers")
- data = res.read().decode("utf-8")
- svlist = json.loads(data)
- for sv in svlist:
- tb = TwitchBot(sv["url"], sv["name"], sv["port"])
- servers[sv["name"]] = tb
- threading.Thread(target=tb.start).start()
- while(1):
- threading.Thread(target=updateLoop).start()
- time.sleep(60)
- else:
- root_logger.error("Error: no database initialized")
- root_logger.warning("Shutting down")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement