Advertisement
Guest User

Untitled

a guest
Jul 24th, 2014
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 26.10 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import faulthandler
  3. faulthandler.enable()
  4. import irc.bot
  5. import irc.strings
  6. from django.utils.html import escape
  7. import sqlite3
  8. import json
  9. try:
  10.     import urllib.request as urllib2
  11. except:
  12.     import urllib2
  13. import datetime
  14. import threading
  15. import time
  16. from time import gmtime, strftime
  17. import logging
  18. import sys
  19. import codecs
  20. import random
  21. import re
  22. from collections import deque
  23. killbot = False
  24.  
  25.  
  26. FORMAT="[%(levelname)s] %(asctime)s - %(message)s"
  27. LOGDIR = "/home/django/django_project/logs/"
  28.  
  29. #logging.basicConfig(filename=LOGDIR+"logviewer_%s.log"%(time.strftime("%Y_%m_%d_%H_%M_%S")),level=logging.INFO,format=FORMAT)
  30. handler = logging.FileHandler(LOGDIR+"slashbot_%s.log"%(time.strftime("%Y_%m_%d"),),"a",encoding = "UTF-8")
  31. formatter = logging.Formatter(FORMAT)
  32. handler.setFormatter(formatter)
  33. root_logger = logging.getLogger()
  34. root_logger.addHandler(handler)
  35. root_logger.setLevel(logging.INFO)
  36.  
  37. #if sys.stdout.encoding != 'cp850':
  38.  # sys.stdout = codecs.getwriter('cp850')(sys.stdout.buffer, 'strict')
  39. #if sys.stderr.encoding != 'cp850':
  40.  # sys.stderr = codecs.getwriter('cp850')(sys.stderr.buffer, 'strict')
  41. if sys.stdout.encoding != 'cp850':
  42.   sys.stdout = codecs.getwriter('cp850')(sys.stdout, 'strict')
  43. if sys.stderr.encoding != 'cp850':
  44.   sys.stderr = codecs.getwriter('cp850')(sys.stderr, 'strict')
  45.  
  46. class SQLRequest:
  47.     def __init__(self, sql, data=[], hasdata=False):
  48.         self.sql = sql
  49.         self.res = []
  50.         self.data = data
  51.         self.done = False
  52.         self.hasdata = hasdata
  53.         self.rowid = None
  54.     def __str__(self):
  55.         return ('{"sql":"%s","res":"%s","data":"%s","done":%s}'%(self.sql,self.res,self.data,self.done)).encode("utf-8").decode("ascii", errors='replace')
  56.  
  57. class SQLiteDriver:
  58.     def __init__(self, dbloc):
  59.         self.queue = deque()
  60.         self.writequeue = deque()
  61.         root_logger.info("Starting database driver")
  62.         self.dbloc = dbloc
  63.         self.lastrow = 0
  64.         self.lastflush = time.time()
  65.         threading.Thread(target=self.run).start()
  66.        
  67.     def execute(self, sql, data, wait):
  68.         myreq = SQLRequest(sql,data)
  69.         myreq.hasdata = sql.startswith("SELECT")
  70.         cnt = 0
  71.         if wait:
  72.             self.queue.append(myreq)
  73.             while(cnt < 1000):
  74.                 if(myreq.done):
  75.                     print("Returning query result: %s"%(myreq,))
  76.                     self.lastrow = myreq.rowid
  77.                     return myreq.res
  78.                 else:
  79.                     cnt += 1
  80.                     time.sleep(0.01)
  81.             root_logger.error("Request timeout: %s"%(myreq,))
  82.         else:
  83.             self.writequeue.append(myreq)
  84.             if(len(self.writequeue)>10 or (time.time()-self.lastflush)>1):
  85.                 self.flushWrite()
  86.             try:
  87.                 print("Adding query %s to writequeue"%(req,))
  88.             except Exception:
  89.                 pass
  90.         return ""
  91.                
  92.     def run(self):
  93.         self.dbconn = sqlite3.connect(self.dbloc,timeout=10)
  94.         c = self.dbconn.cursor()
  95.         while(1):
  96.             try:
  97.                 c.execute("begin")
  98.                 didsth = False
  99.                 while self.queue:
  100.                     didsth = True
  101.                     cnt = 0
  102.                     req = self.queue.popleft()
  103.                     root_logger.debug("Executing query: %s"%(req,))
  104.                     le = 0
  105.                     while(cnt<10 and cnt>=0):
  106.                         try:
  107.                             r = c.execute(req.sql,req.data)
  108.                             if(req.hasdata):
  109.                                 req.res = r.fetchall()
  110.                             req.rowid = r.lastrowid
  111.                             req.done = True
  112.                             cnt = -1
  113.                             break
  114.                         except Exception as e:
  115.                             cnt += 1
  116.                             time.sleep(0.01)
  117.                             le = e
  118.                             root_logger.exception(e)
  119.                             root_logger.error(req.sql)
  120.                             root_logger.error(req.data)
  121.                             pass
  122.                     if(cnt>=10):
  123.                         print("QUEUE ERROR")
  124.                 if not didsth:
  125.                     time.sleep(0.01)
  126.                 self.dbconn.commit()
  127.             except Exception as e:
  128.                 root_logger.exception(e)
  129.                 print(e)
  130.                 try:
  131.                     c.execute("rollback")
  132.                 except Exception:
  133.                     pass
  134.                 pass
  135.    
  136.     def flushWrite(self):
  137.         print("FLUSHING QUEUE")
  138.         self.queue.extend(self.writequeue)
  139.         self.writequeue = deque()
  140.         self.lastflush = time.time()
  141.        
  142.        
  143.                    
  144.                    
  145. class TwitchChannel:
  146.     def __init__(self, ch, sv):
  147.         self.channel = "#"+ch
  148.         self.twitchch = ch
  149.         self.twitchsv = sv
  150.         self.active = True
  151.         self.specialusers = []
  152.         self.subscribers = []
  153.         self.lastchallenge = dict()
  154.         self.challenger = dict()
  155.         self.updateSpecialusers()
  156.         self.ops = []
  157.     def getRepr(self):
  158.         return {"name":self.twitchch,"server":self.twitchsv,"active":self.active}
  159.     def updateSpecialusers(self):
  160.         try:
  161.             res = pointdb.execute("SELECT User,Level FROM points_%s WHERE Level>0"%(self.twitchch,),[],True)
  162.             self.specialusers = dict()
  163.             for row in res:
  164.                 self.specialusers[row[0]] = int(row[1])
  165.         except Exception as e:
  166.             root_logger.exception(e)
  167.     def getUserLevel(self,user):
  168.         x = 0
  169.         if user in self.specialusers:
  170.             x = self.specialusers[user]
  171.         if user in self.subscribers:
  172.             x = max(x,2)
  173.         if user in self.ops:
  174.             x = max(x,5)
  175.         return x
  176.        
  177.  
  178. class TwitchBot(irc.bot.SingleServerIRCBot):
  179.     def __init__(self, server, servername, port=6667):
  180.         irc.bot.SingleServerIRCBot.__init__(self, [(server, port,"oauth:dbjkzu3xne12ug2ml7t0ugsk4ubxkai")], "InternetPoinz", "InternetPoinz")
  181.         try:
  182.             self.twitchsv = servername
  183.             self.twitchchs = dict()
  184.             self.welcomed = False
  185.             root_logger.info("Bot for "+self.twitchsv+" created.")
  186.             self.sendqueue = deque()
  187.             self.cc = None
  188.             print("Bot for "+self.twitchsv+" created.")
  189.             threading.Thread(target=self.sendAgent).start()
  190.         except Exception as e:
  191.             root_logger.exception(e)
  192.        
  193.     def joinChannel(self,chanU):
  194.         chan = chanU.lower()
  195.         self.ensureTableExists(chan)
  196.         changedsince[chan] = False
  197.         ch = TwitchChannel(chan,self.twitchsv)
  198.         root_logger.info("Joining channel "+chan)
  199.         if(self.welcomed):
  200.             self.connection.join(ch.channel)
  201.             print("Channel "+chan+" joined")
  202.             root_logger.info("Channel "+chan+" joined")
  203.         self.twitchchs[chan] = ch
  204.        
  205.     def leaveChannel(self,chan):
  206.         if(chan in self.twitchchs.keys()):
  207.             if(self.welcomed):
  208.                 print("Leaving channel "+chan)
  209.                 root_logger.info("Leaving channel "+chan)
  210.                 self.connection.part(self.twitchchs[chan].channel)
  211.             self.twitchchs.__delitem__(chan)
  212.        
  213.     def on_welcome(self, c, e):
  214.         c.send_raw("twitchclient 3")
  215.         root_logger.info("Connected to server "+self.twitchsv)
  216.         print("Connected to server "+self.twitchsv)
  217.         for ch in self.twitchchs:
  218.             self.connection.join(self.twitchchs[ch].channel)
  219.             print("On welcome: Channel "+ch+" joined.")
  220.             root_logger.info("On welcome: Channel "+ch+" joined.")
  221.         self.welcomed = True
  222.        
  223.     def on_pubmsg(self, c, e):
  224.         self.cc = c
  225.         self.addLine(e.target.replace("#",""),e.source.nick, e.arguments[0])
  226.        
  227.     def on_privmsg(self, c, e):
  228.         self.cc = c
  229.         self.addLine(e.target.replace("#",""),e.source.nick, e.arguments[0])
  230.  
  231.     def on_ctcp(self, c, e):
  232.         self.cc = c
  233.         self.addLine(e.target.replace("#",""),e.source.nick, e.arguments[1])
  234.        
  235.     def on_mode(self, c, e):
  236.         chan = ""
  237.         try:
  238.             chan = self.twitchchs[e.target.replace("#","")]
  239.         except:
  240.             return
  241.             pass
  242.         if len(e.arguments)==2:
  243.             if e.arguments[0]=="+o":
  244.                 if e.arguments[1] not in chan.ops:
  245.                     chan.ops.append(e.arguments[1])
  246.                     print("added %s as op"%e.arguments[1])
  247.             elif e.arguments[0]=="-o":
  248.                 if e.arguments[1] in chan.ops:
  249.                     chan.ops.remove(e.arguments[1])
  250.                     print("removed %s as op"%e.arguments[1])
  251.                    
  252.     def sendAgent(self):
  253.         while(1):
  254.             try:
  255.                 if len(self.sendqueue) > 0:
  256.                     x = self.sendqueue.popleft()
  257.                     self.cc.privmsg("#"+x[0],x[1])
  258.                     print("--> #"+x[0]+": "+x[1])
  259.                     time.sleep(2)
  260.                 else:
  261.                     time.sleep(1)
  262.             except Exception as e:
  263.                 root_logger.exception(e)
  264.                 pass
  265.        
  266.     def sendLine(self,ch,text):
  267.         self.sendqueue.append((ch,text))
  268.        
  269.     def addLine(self, channel, nick, text):
  270.         try:
  271.             print(nick+": "+text)
  272.         except:
  273.             pass
  274.         chan = ""
  275.         try:
  276.             chan = self.twitchchs[channel]
  277.         except:
  278.             return
  279.             pass
  280.         try:
  281.             if nick=="jtv":
  282.                 ex = text.split(" ",2)
  283.                 for i in range(len(ex)):
  284.                     ex[i] = ex[i].strip().lower()
  285.                 if ex[0] == "specialuser":
  286.                     if ex[2] == "subscriber" and ex[1] not in chan.subscribers:
  287.                         chan.subscribers.append(ex[1])
  288.                         print("Added %s as subscriber"%(ex[1]))
  289.                
  290.             if text.startswith("!"):
  291.                 lv = chan.getUserLevel(nick)
  292.                 ex = text.split(" ",1)
  293.                 ex2 = []
  294.                 ex2.extend(ex)
  295.                 if len(ex)>0:
  296.                     for i in range(len(ex)):
  297.                         ex[i] = ex[i].strip().lower()
  298.                     if lv>=chan.getUserLevel(ex[0]):
  299.                         if ex[0] == "!level":
  300.                             if len(ex)==2:
  301.                                 d = ex[1].split()
  302.                                 if len(d)==1:
  303.                                     self.sendLine(channel,"Userlevel of %s is %s"%(d[0],chan.getUserLevel(d[0])))
  304.                                 elif len(d)==2:
  305.                                     try:
  306.                                         nlv = int(d[1])
  307.                                         if nlv<lv and chan.getUserLevel(d[0])<lv:
  308.                                             pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(channel,),[d[0],nlv],True)
  309.                                             pointdb.execute(("UPDATE OR IGNORE points_%s SET Level=(?) WHERE User=(?)")%(channel,),[nlv,d[0]],True)
  310.                                             self.sendLine(channel,"Set userlevel of %s from %s to %s"%(d[0],chan.getUserLevel(d[0]),nlv))
  311.                                             chan.updateSpecialusers()
  312.                                         else:
  313.                                             self.sendLine(channel,"Cannot set userlevel of %s: Access denied."%(d[0],))
  314.                                     except Exception as e:
  315.                                         self.sendLine(channel,"Userlevel %s invalid"%(d[1]))
  316.                                         root_logger.exception(e)
  317.                                         pass
  318.                         if ex[0] == "!removeme":
  319.                             pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(channel),),(nick,-9999999),False)
  320.                             pointdb.execute("UPDATE points_%s SET Points=-99999999 WHERE User=?"%getTableUser(channel),(nick,),False)
  321.                             changedsince[channel] = True
  322.                             self.sendLine(channel,"Removed user %s from the points bot."%(nick,))
  323.                         if ex[0] == "!remove":
  324.                             if len(ex)==2:
  325.                                 pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(channel),),(ex[1].lower(),-9999999),False)
  326.                                 pointdb.execute("UPDATE points_%s SET Points=-99999999 WHERE User=?"%getTableUser(channel),(ex[1].lower(),),False)
  327.                                 changedsince[channel] = True
  328.                                 self.sendLine(channel,"Removed user %s from the points bot."%(ex[1],))
  329.                                    
  330.                         if ex[0] == "!give":
  331.                             if len(ex)==2:
  332.                                 d = ex[1].strip().split(" ",1)
  333.                                 if len(d)==2:
  334.                                     try:
  335.                                         ps = int(d[1])
  336.                                         usr = d[0].lower().strip()
  337.                                         if usr=="everyone":
  338.                                             pointdb.execute("UPDATE OR IGNORE points_%s SET Points=Points+(?) WHERE Points>0 AND User NOT LIKE '!%%'"%getTableUser(channel),(d[1],),False)
  339.                                             changedsince[channel] = True
  340.                                             self.sendLine(channel,"Gave everyone %s points."%(d[1],))
  341.                                         elif usr=="chatters":
  342.                                             give_chatters(channel,d[1])
  343.                                             changedsince[channel] = True
  344.                                             self.sendLine(channel,"Gave everyone currently in chat %s points."%(d[1],))
  345.                                         else:
  346.                                             pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(channel),),(usr,0),False)
  347.                                             pointdb.execute("UPDATE OR IGNORE points_%s SET Points=Points+(?) WHERE User=(?)"%getTableUser(channel),(d[1],usr,),False)
  348.                                             changedsince[channel] = True
  349.                                             if usr.startswith("!"):
  350.                                                 self.sendLine(channel,"Increased point setting on command %s by %s points."%(usr,d[1]))
  351.                                             else:
  352.                                                 self.sendLine(channel,"Gave user %s %s points."%(usr,d[1]))
  353.                                     except Exception as e:
  354.                                         print("Error in !give: "+str(e))
  355.                                         pass
  356.                             pointdb.flushWrite()
  357.                            
  358.                         if ex[0] == "!boost":
  359.                             if len(ex)==2:
  360.                                 d = ex[1].strip().split(" ",1)
  361.                                 try:
  362.                                     duration = int(d[0]) # in 10 minute ticks
  363.                                     powah = ""
  364.                                     if len(d)==2:
  365.                                         try:
  366.                                             power = int(d[1])
  367.                                             pointdb.execute("UPDATE OR IGNORE points_%s SET Points=(?) WHERE User=(?)"%getTableUser(channel),(d[1],"!boost-power",),False)
  368.                                             powah = " with boost power %d"%(power,)
  369.                                         except Exception as e:
  370.                                             root_logger.exception(e)
  371.                                             print(e)
  372.                                             pass
  373.                                     pointdb.execute("UPDATE OR IGNORE points_%s SET Points=(?) WHERE User=(?)"%getTableUser(channel),(d[0],"!boost",),False)
  374.                                     if duration>0:
  375.                                         hrs = int(duration/6)
  376.                                         mins = (duration%6)*10
  377.                                         dstr = ""
  378.                                         if(hrs>0):
  379.                                             dstr = " %d hour"%(hrs,)
  380.                                         if(mins>0):
  381.                                             dstr += " %d minute"%(mins,)
  382.                                         self.sendLine(channel,"Set%s boost on channel %s%s."%(dstr,channel,powah))
  383.                                     else:
  384.                                         self.sendLine(channel,"Removed boost on channel %s."%(channel,))
  385.                                     pointdb.flushWrite()
  386.                                 except Exception as e:
  387.                                     root_logger.exception(e)
  388.                                     print(e)
  389.                                     pass
  390.                             else:
  391.                                 pts = 1
  392.                                 try:
  393.                                     res = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),("!boost",),True)
  394.                                     for row in res:
  395.                                         duration = int(row[0]) # in 10 minute ticks
  396.                                         if(duration>0):
  397.                                             if duration>0:
  398.                                                 hrs = int(duration/6)
  399.                                                 mins = (duration%6)*10
  400.                                                 dstr = ""
  401.                                                 if(hrs>0):
  402.                                                     dstr = " %d hours"%(hrs,)
  403.                                                 if(mins>0):
  404.                                                     dstr += " %d minutes"%(mins,)
  405.                                                 res2 = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),("!boost-power",),True)
  406.                                                 for row2 in res2:
  407.                                                     pts = int(row2[0])
  408.                                                     self.sendLine(channel,"Channel %s is boosted for%s with boost power %d."%(channel,dstr,pts))
  409.                                                 break
  410.                                             else:
  411.                                                 self.sendLine(channel,"Channel %s is not boosted."%(channel,))
  412.                                 except Exception as e:
  413.                                     root_logger.exception(e)
  414.                                     print(e)
  415.                                     pass
  416.                                 pointdb.flushWrite()
  417.                                
  418.                            
  419.                         if ex[0] == "!set":
  420.                             if len(ex)==2:
  421.                                 d = ex[1].strip().split(" ",1)
  422.                                 if len(d)==2:
  423.                                     try:
  424.                                         ps = int(d[1])
  425.                                         usr = d[0].lower().strip()
  426.                                         if usr=="everyone":
  427.                                             pointdb.execute("UPDATE OR IGNORE points_%s SET Points=(?) WHERE Points>0 AND User NOT LIKE '!%'"%getTableUser(channel),(d[1],),False)
  428.                                             self.sendLine(channel,"Set everyones points to %s."%(d[1],))
  429.                                             changedsince[channel] = True
  430.                                         elif usr=="chatters":
  431.                                             set_chatters(channel,d[1])
  432.                                             self.sendLine(channel,"Set the points of everyone currently in chat to %s."%(d[1],))
  433.                                             changedsince[channel] = True
  434.                                         else:
  435.                                             pointdb.execute("UPDATE OR IGNORE points_%s SET Points=(?) WHERE User=(?)"%getTableUser(channel),(d[1],usr),False)
  436.                                             if usr.startswith("!"):
  437.                                                 self.sendLine(channel,"Set the point setting on command %s to %s points."%(usr,d[1]))
  438.                                             else:
  439.                                                 self.sendLine(channel,"Set the points of user %s to %s."%(usr,d[1]))
  440.                                             changedsince[channel] = True
  441.                                     except:
  442.                                         pass
  443.                             pointdb.flushWrite()
  444.                                        
  445.                         if ex[0] == "!points":
  446.                             if len(ex)==2:
  447.                                 try:
  448.                                     res = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),(ex[1],),True)
  449.                                     for row in res:
  450.                                         p=0
  451.                                         try:
  452.                                             p = int(row[0])
  453.                                         except Exception:
  454.                                             pass
  455.                                         if p>=0:
  456.                                             if ex[1].startswith("!"):
  457.                                                 self.sendLine(channel,"Points setting on command %s is %s."%(ex[1],row[0]))
  458.                                             else:
  459.                                                 self.sendLine(channel,"User %s has %s points."%(ex[1],row[0]))
  460.                                         else:
  461.                                             if ex[1].startswith("!"):
  462.                                                 self.sendLine(channel,"Point cap for %s has been disabled."%(ex[1],))
  463.                                             else:
  464.                                                 self.sendLine(channel,"User %s has been removed from the leaderboards."%(ex[1],))
  465.                                 except:
  466.                                     pass
  467.                             elif len(ex)==1:
  468.                                 try:
  469.                                     res = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),(nick,),True)
  470.                                     for row in res:
  471.                                         p=0
  472.                                         try:
  473.                                             p = int(row[0])
  474.                                         except Exception:
  475.                                             pass
  476.                                         if p>=0:
  477.                                             self.sendLine(channel,"User %s has %s points."%(nick,row[0]))
  478.                                         else:
  479.                                             self.sendLine(channel,"User %s has been removed from the leaderboards."%(nick,))
  480.                                 except:
  481.                                     pass
  482.                                    
  483.                         if ex[0] == "!forceupdate":
  484.                             pointdb.flushWrite()
  485.                             time.sleep(1)
  486.                             cc = channel
  487.                             if len(ex)==2:
  488.                                 cc = ex[1]
  489.                             ccc = getTableUser(cc)
  490.                             threading.Thread(target=open_website, args=[baseurl+"/api/updatepoints/"+getTableUser(ccc)]).start()
  491.                             changedsince[channel] = False
  492.                             if(ccc==cc):
  493.                                 self.sendLine(channel,"Forcibly updated points leaderboard for channel %s."%(ccc,))
  494.                             else:
  495.                                 self.sendLine(channel,"Forcibly updated points leaderboard for linked channel %s."%(ccc,))
  496.                                    
  497.                         if ex[0] == "!help":
  498.                             self.sendLine(channel,"Help and command list: slashcaststd.com/slashbot/lv/help/")
  499.                                
  500.                                            
  501.                         if ex[0] == "!leaderboard":
  502.                             self.sendLine(channel,"Slash Generals leaderboard: slashcaststd.com/slashbot/leaderboard")
  503.                            
  504.                         if ex[0] == "!army":
  505.                             self.sendLine(channel,"Manage your minions at slashcaststd.com/slashbot/")
  506.                            
  507.                            
  508.                         if ex[0] == "!challenge":
  509.                             if len(ex)==2:
  510.                                 lt = datetime(1970,1,1)
  511.                                 if(nick in chan.lastchallenge):
  512.                                     lt = chan.lastchallenge[nick]
  513.                                 dt = (datetime.datetime.now - lt).total_seconds()
  514.                                 if dt>=180:
  515.                                     lt = datetime(1970,1,1)
  516.                                     if(ex[1] in chan.lastchallenge):
  517.                                         lt = chan.lastchallenge[ex[1]]
  518.                                     dt = (datetime.datetime.now - lt).total_seconds()
  519.                                     if dt < 180:
  520.                                         self.sendLine(channel,"User %s has a challenge running. In %d minutes, the challenge will run out."%(ex[1],int(dt/60)))
  521.                                     else:
  522.                                         chan.lastchallenge[nick] = datetime.datetime.now
  523.                                         chan.lastchallenge[ex[1]] = datetime.datetime.now
  524.                                         chan.challenger[ex[1]] = nick
  525.                                         self.sendLine(channel,"User %s has challenged %s to a duel! %s, type !accept to accept the duel request!"%(ex[1],int(dt/60)))
  526.                                        
  527.                         if ex[0] == "!accept":
  528.                             if nick in chan.challenger:
  529.                                 p = [chan.challenger[nick],nick]
  530.                                 # grab data
  531.                                 res = pointdb.execute("SELECT User,Army,ArmySize FROM points_%s WHERE User=(?) OR User=(?)"%(channel,),(p[0],p[1]))
  532.                                
  533.                            
  534.                         if ex[0] == "!test":
  535.                             if len(ex) == 1:
  536.                                 self.sendLine(channel,"Test reply to "+nick+" sent at "+strftime("%a, %d %b %Y %H:%M:%S UTC", gmtime()))
  537.                             else:
  538.                                 self.sendLine(channel,"Test reply to %s sent at %s (%s)"%(nick,strftime("%a, %d %b %Y %H:%M:%S UTC", gmtime()),ex[1]))
  539.                            
  540.         except Exception as e:
  541.             root_logger.exception(e)
  542.             try:
  543.                 print(e)
  544.             except:
  545.                 pass
  546.             pass
  547.    
  548.     def ensureTableExists(self, ch):
  549.         print("Creating tables for "+getTableUser(ch))
  550.         pointdb.execute(("CREATE TABLE IF NOT EXISTS [points_%s] ("
  551.                             "[User] TEXT PRIMARY KEY NOT NULL,"
  552.                             "[Points] INTEGER DEFAULT '0' NOT NULL,"
  553.                             "[TotalPoints] INTEGER DEFAULT '0' NOT NULL,"
  554.                             "[Level] INTEGER DEFAULT '0' NOT NULL,"
  555.                             "[Army] TEXT DEFAULT (?) NOT NULL,"
  556.                             "[ArmySize] INTEGER DEFAULT '0' NOT NULL,"
  557.                             "[Oauth] TEXT DEFAULT '' NOT NULL"
  558.                             ")")%(ch,),['[0,0,0,0]',],True)
  559.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),[ch,10],False)
  560.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["cbenni",1337],False)
  561.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!give",9],False)
  562.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!set",9],False)
  563.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!remove",9],False)
  564.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!forceupdate",9],False)
  565.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!level",5],False)
  566.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!test",5],False)
  567.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!points",1],False)
  568.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!leaderboard",1],False)
  569.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!army",1],False)
  570.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!help",1],False)
  571.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!challenge",0],False)
  572.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!accept",0],False)
  573.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!decline",0],False)
  574.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level) VALUES (?,?)")%(ch,),["!removeme",0],False)
  575.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level,Points) VALUES (?,?,?)")%(ch,),["!boost",9,0],False)
  576.         pointdb.execute(("INSERT OR IGNORE INTO points_%s (User,Level,Points) VALUES (?,?,?)")%(ch,),["!boost-power",999,2],False)
  577.         pointdb.execute(("CREATE INDEX IF NOT EXISTS armyindex_%s ON points_%s (ArmySize DESC)")%(ch,ch),[],False)
  578.         pointdb.flushWrite()
  579.         print("Done creating table for "+ch)
  580.        
  581.        
  582. def getTableUser(usr):
  583.     return usr
  584.  
  585. def open_website(url):
  586.     root_logger.debug(urllib2.urlopen(url))
  587.    
  588. def give_chatters(cc,pts):
  589.     try:
  590.         res = urllib2.urlopen("http://tmi.twitch.tv/group/user/%s/chatters"%cc)
  591.         data = res.read().decode("utf-8")
  592.         chatterdata = json.loads(data)
  593.         cats = ["moderators","staff","admins","viewers"]
  594.         for cat in cats:
  595.             for v in chatterdata["chatters"][cat]:
  596.                 pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(cc),),(v,0),False)
  597.                 pointdb.execute("UPDATE points_%s SET Points=Points+(?) WHERE User=(?)"%getTableUser(cc),(pts,v),False)
  598.         changedsince[cc] = True
  599.     except Exception as e:
  600.         root_logger.exception(e)
  601.         print("error: "+str(e))
  602.         pass
  603.            
  604. def set_chatters(cc,pts):
  605.     try:
  606.         res = urllib2.urlopen("http://tmi.twitch.tv/group/user/%s/chatters"%cc)
  607.         data = res.read().decode("utf-8")
  608.         chatterdata = json.loads(data)
  609.         cats = ["moderators","staff","admins","viewers"]
  610.         for cat in cats:
  611.             for v in chatterdata["chatters"][cat]:
  612.                 pointdb.execute("INSERT OR IGNORE INTO points_%s (User,Points) VALUES (?,?)"%(getTableUser(cc),),(v,0),False)
  613.                 pointdb.execute("UPDATE points_%s SET Points=(?) WHERE User=(?)"%getTableUser(cc),(pts,v),False)
  614.         changedsince[cc] = True
  615.     except Exception as e:
  616.         root_logger.exception(e)
  617.         print("error: "+str(e))
  618.         pass
  619.  
  620.  
  621. def getPointsPerTick(channel,islive):
  622.     pts = 1
  623.     if islive:
  624.         pts = 25
  625.     try:
  626.         res = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),("!boost",),True)
  627.         for row in res:
  628.             if(int(row[0])>0):
  629.                 res2 = pointdb.execute("SELECT (Points) FROM points_%s WHERE User=(?)"%getTableUser(channel),("!boost-power",),True)
  630.                 for row2 in res2:
  631.                     pts = int(row2[0])
  632.                     pointdb.execute("UPDATE OR IGNORE points_%s SET Points=Points-1 WHERE User=(?)"%getTableUser(channel),("!boost",),False)
  633.                     print("Channel %s is boosted with power %d"%(channel,pts))
  634.                 break
  635.     except Exception as e:
  636.         root_logger.exception(e)
  637.         print(e)
  638.         pass
  639.     pointdb.flushWrite()
  640.     return pts
  641.  
  642. def updateLoop():
  643.     global kappalist
  644.     global coincounter
  645.     try:
  646.         root_logger.debug("Starting update loop.")
  647.         # get coinchannels
  648.         res = urllib2.urlopen(baseurl+"/api/channels")
  649.         data = res.read().decode("utf-8")
  650.         chdata = json.loads(data)
  651.         tmpchdata = []
  652.         # kill removed/changed bots
  653.         # tmpchdata contains those bots that survive
  654.         # additionally, we update the specialusers
  655.         for svr in servers:
  656.             sv = servers[svr]
  657.             for ch in sv.twitchchs:
  658.                 cd = sv.twitchchs[ch].getRepr()
  659.                 if cd in chdata:
  660.                     tmpchdata.append(cd)
  661.                 else:
  662.                     root_logger.info("Killing bot "+str(cd))
  663.                     sv.leaveChannel(ch)
  664.         for cd in chdata:
  665.             if(cd not in tmpchdata and cd["active"]==True):
  666.                 root_logger.info("Deploying bot "+str(cd))
  667.                 servers[cd["server"]].joinChannel(cd["name"])
  668.                
  669.         # now we collect some data...
  670.         chstring = ""
  671.         livechans = []
  672.         firstch = True
  673.         try:
  674.             res = urllib2.urlopen("http://api.justin.tv/api/stream/list.json?channel="+",".join(coindata))
  675.             data = res.read().decode("utf-8")
  676.             streamdata = json.loads(data)
  677.             for stream in streamdata:
  678.                 livechans.append(stream["channel"]["title"])
  679.         except Exception as e:
  680.             print("Exception when trying to get live streams")
  681.             print(e)
  682.             root_logger.exception(e)
  683.             pass
  684.  
  685.         coincounter = coincounter+1
  686.         chcounter=0
  687.         try:
  688.             print(changedsince)
  689.         except:
  690.             pass
  691.         try:
  692.             for coinchan in coindata:
  693.                 cc = coinchan.lower()
  694.                 if (coincounter+chcounter)%60==2:
  695.                     pts = getPointsPerTick(cc,coinchan in livechans)
  696.                     give_chatters(cc,pts)
  697.                 if (coincounter+chcounter)%60==32 and coinchan in livechans:
  698.                     pts = getPointsPerTick(cc,True)
  699.                     give_chatters(cc,pts)
  700.                 if (coincounter+chcounter)%10==3:
  701.                     if(changedsince[cc] == True):
  702.                         print("Updating points for "+coinchan)
  703.                         threading.Thread(target=open_website, args=[baseurl+"/api/updatepoints/"+cc]).start()
  704.                         changedsince[cc] = False
  705.                     else:
  706.                         print("Not updating points for "+coinchan)
  707.                        
  708.                 chcounter = chcounter+1
  709.         except Exception as e:
  710.             root_logger.exception(e)
  711.             print(e)
  712.             pass
  713.         pointdb.flushWrite()
  714.     except Exception as e:
  715.         root_logger.exception(e)
  716.         pass
  717.  
  718. baseurl = "http://127.0.0.1/slashminion"
  719. res = urllib2.urlopen(baseurl+"/api/databases")
  720. data = res.read().decode("utf-8")
  721. info = json.loads(data)
  722. servers = {}
  723. coincounter = 0
  724. changedsince = dict()
  725. if(info):
  726.     pointdbloc = info["points"]["url"]
  727.     pointdb =  SQLiteDriver(pointdbloc)
  728.     res = urllib2.urlopen(baseurl+"/api/servers")
  729.     data = res.read().decode("utf-8")
  730.     svlist = json.loads(data)
  731.     for sv in svlist:
  732.         tb = TwitchBot(sv["url"], sv["name"], sv["port"])
  733.         servers[sv["name"]] = tb
  734.         threading.Thread(target=tb.start).start()
  735.     while(1):
  736.         threading.Thread(target=updateLoop).start()
  737.         time.sleep(60)
  738. else:
  739.     root_logger.error("Error: no database initialized")
  740. root_logger.warning("Shutting down")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement