def handleMsg(s, dik, modstatus, chan, user, message): try: uloste, b = message.split(' ', 1) b = b.strip() except: uloste = message.strip() b = "" try: modonlycmd = 0 uloste = str(uloste) if chan.startswith("jtv"): uloste = dik["jtv"][uloste.lower().decode('utf8')] else: uloste = dik[chan][uloste.lower().decode('utf8')] if uloste != None: if '$user$' in uloste: uloste = uloste.replace('$user$', user) if '$mod$' in uloste: uloste = uloste.replace('$mod$', "") modonlycmd = 1 if '$uptime$' in uloste: uloste = uloste.replace('$uptime$', getUptime(chan)) if '$random100$' in uloste: uloste = uloste.replace('$random100$', str(randint(0, 100))) if '$d20$' in uloste: uloste = uloste.replace('$d20$', str(randint(1, 20))) if '$d6$' in uloste: uloste = uloste.replace('$d6$', str(randint(1, 6))) # this last so !paikal $random100$ doesnt work if '$own$' in uloste: uloste = uloste.replace('$own$', b) if not modonlycmd: sendChanMsg(s, chan, uloste) elif modonlycmd: modonlycmd = 0 if modstatus and uloste != "": sendChanMsg(s, chan, uloste) except Exception, e: #print "handlemsg error:", e pass
def addcom(s, dik, chan, user, message): try: if chan.startswith("jtv"): cmds = dik["jtv"] else: cmds = dik[chan] a, b = message.split('!addcom ', 1) c, d = b.split(' ', 1) #if c.startswith("!") == False: # c = '!' + c cmd = c.decode('utf8') if cmd.endswith(':'): cmd = cmd.replace(':', '') action = d.decode('utf8') action = action.strip().decode('utf8') cmd = cmd.strip().lower().decode('utf8') toAdd = {cmd: action} cmdDoesExist = cmds.get(cmd) if cmdDoesExist == None: cmds.update(toAdd) dik.update(cmds) if chan.startswith("jtv"): json.dump(cmds, open("jtvcommands", 'wb'), sort_keys=True, indent=3) else: json.dump(cmds, open(chan.strip() + "commands", 'wb'), sort_keys=True, indent=3) resp = "[ADDED]: " + cmd + " : " + action chan = "jtv," + user sendChanMsg(s, chan, resp) else: resp = cmd + " : " + cmdDoesExist + " already exists, please !delcom it first" chan = "jtv,"+user sendChanMsg(s, chan, resp) except Exception, e: print "addcom error:", e
def delcom(s, dik, chan, user, message): try: if chan.startswith("jtv"): cmds = dik["jtv"] else: cmds = dik[chan] a, b = message.split('!delcom ', 1) #if b.startswith("!") == False: # b = '!' + b poistettava = b.strip().lower().decode('utf8') action = cmds.get(poistettava) if action != None: del cmds[poistettava] dik.update(cmds) resp = "[DELETED]: " + poistettava + " : " + action if chan.startswith("jtv"): json.dump(cmds, open("jtvcommands", 'wb'), sort_keys=True, indent=3) else: json.dump(cmds, open(chan.strip() + "commands", 'wb'), sort_keys=True, indent=3) chan = "jtv," + user sendChanMsg(s, chan, resp) except Exception, e: print "delcom error:", e
def main_loop(): import os import sys import ftplib import string import select import fileinput from timeit import default_timer as timer from time import sleep, time from datetime import datetime, timedelta from Read import getUser, getMessage, getChannel from Socket import openSocket, sendMessage, sendChanMsg, joinChan, quitChan from Init import joinRoom from Logger import log from Api import getUptime, updateMods, restartbot, getSteamStats, convertToSteam64 from Messagecommands import tryCommands s = openSocket() joinRoom(s) s.setblocking(0) readbuffer = "" num = 0 elapsed = 0 end = 0 dt_uptime = 0 downtime = 0 reload(sys) sys.setdefaultencoding("utf8") # s.send("CAP REQ :twitch.tv/membership") # s.send("CAP REQ :twitch.tv/commands") # s.send("CAP REQ :twitch.tv/tags") sendChanMsg(s, "finnishforce_", "started") while 1: start = timer() temp = "" user = "" try: getit = s.recv(4096) # print getit readbuffer = readbuffer + getit temp = string.split(readbuffer, "\n") readbuffer = temp.pop() except: sleep(0.5) if temp != "": for line in temp: try: if "PING :tmi.twitch.tv" in line.strip(): s.send("PONG :tmi.twitch.tv\r\n") break else: if "PRIVMSG" in getit: user = getUser(line).encode("utf8") message = getMessage(line).encode("utf8") chan = getChannel(line).encode("utf8") time = datetime.now().strftime("%Y-%d-%m %H:%M:%S") toLog = user.decode("utf-8") + ": " + message.decode("utf-8") log(toLog, chan) else: sleep(0.1) except: print "error ping" if temp != "": if "PRIVMSG" in getit: tryCommands(s, chan, user, message) # does not work after adding messagecommands.py, need new implementation # if message.startswith("!softresetbot"): # if user.strip().lower() == "finnishforce_": # sendChanMsg(s, chan, "DONE!") # execfile("/home/pi/Desktop/ForceBotti/Run.py") end = timer() elapsed = elapsed + (end - start) if elapsed >= 300: s.send("PONG :tmi.twitch.tv\r\n") elapsed = 0
def tryCommands(s, chan, user, message): import os import sys import ftplib import string import select import fileinput from timeit import default_timer as timer from time import sleep, time from datetime import datetime, timedelta from Read import getUser, getMessage, getChannel from Socket import openSocket, sendMessage, sendChanMsg, joinChan, quitChan from Init import joinRoom from Logger import log num = 0 addc = 0 delc = 0 exists = 0 worked = 0 kaisanetacc = REDACTED kaisanetpass = REDACTED delthis = "" chancmds = chan + 'commands.txt' with open(chancmds, 'a+') as cmdfile: commands = cmdfile.readlines() chanmods = chan + 'mods.txt' with open(chanmods, 'a+') as modsfile: mods = modsfile.readlines() if message.startswith("!rng"): try: u, a = message.split("!rng ") print u, a a, b = a.split(" ") r = randint(int(a), int(b)) resp = "You got " + str(r) sendChanMsg(s, chan, resp) except: print "rng error" if message.startswith("!joinlobby"): try: resp = getJoin() sendChanMsg(s, chan, resp) except: print "!join error wot" if message.startswith("!botjoin"): try: joinhere = user.strip() joinChan(s, joinhere) except: print "joinchan in mainloop error" if message.startswith("!botquit"): try: quithere = user.strip() resp = ("leaving from channel #" + quithere + ", goodbye") sendChanMsg(s, chan, resp) quitChan(s, quithere) except: print "quitchan in mainloop error" if message.startswith("!cpustats"): try: cpu_temperature = get_cpu_temperature() cpu_usage = psutil.cpu_percent() resp1 = "CPU usage: " + str(cpu_usage) + "%" + " | CPU temperature: " + str(cpu_temperature) + "C" sendChanMsg(s, chan, resp1) except: log("cpustats error", "globalerror") if message.startswith("!restartbot"): for modnames in mods: if modnames.strip().lower() == user.strip().lower() or user.strip() == "finnishforce_": try: sendChanMsg(s, chan, "restarting bot, brb 1-2 min") restartbot() except: print "error in restartbotrun.py" if message.startswith("!uptime"): try: uptime = getUptime(chan) sendChanMsg(s, chan, uptime) except: log("uptime error", "globalerror") if message.startswith("!pyramid"): try: if user.strip() == "finnishforce_" or user.strip() == chan.strip(): a, b = message.split('!pyramid') temp = b sendChanMsg(s, chan, temp) sleep(0.1) temp = b+b sendChanMsg(s, chan, temp) sleep(0.1) temp = b+b+b sendChanMsg(s, chan, temp) sleep(0.1) temp = b+b+b+b sendChanMsg(s, chan, temp) sleep(0.1) temp = b+b+b sendChanMsg(s, chan, temp) sleep(0.1) temp = b+b sendChanMsg(s, chan, temp) sleep(0.1) temp = b sendChanMsg(s, chan, temp) sleep(0.1) except: print "pyramid error" if message.startswith("!updatemods"): try: updateMods(chan) except: print "updatemods error" if message.startswith("!updatecommands"): try: session = ftplib.FTP('ftp.kaisanet.net', kaisanetacc, kaisanetpass) file = open('susihukka2551commands.txt', 'rb') session.storbinary('STOR susihukka2551commands.txt', file) file.close() session.quit() except: print "updatecommands error" if message.startswith("!Laddcom") or message.startswith("!laddcom"): try: with open(chancmds, 'a+') as cmdfile: for names in mods: if names.strip().lower() == user.strip().lower(): try: a, b = message.split('m !', 1) c, d = b.split(': ', 1) c = '!' + c cmd = c.decode('utf8') action = d.decode('utf8') for sueless in commands: if commands[addc].strip().lower().decode('utf8') == cmd.strip().lower(): response = ("Command already exists " + commands[addc].strip() + " = " + commands[addc+2] + " please !delcom !" + commands[addc].strip() + "first") exists = 1 sendChanMsg(s, chan, response) break if commands[addc].strip().lower().decode('utf8') == action.strip().lower(): response = ("Same action already exists in command " + commands[addc-2].strip() + " = " + commands[addc] + " please !delcom !" + commands[addc-2].strip() + "first") exists = 1 sendChanMsg(s, chan, response) break addc = addc + 1 if action.startswith("!"): action = action.replace('!', '') if exists != 1: cmdfile.write('\n'.encode('utf8') + cmd.encode('utf8') + '\n\n'.encode('utf8') + action.encode('utf8') + '\n'.encode('utf8')) toLog = user + " added command " + cmd + " that does action: " + action.strip() info = chan + "reports" resp = "added " + cmd.strip() + " : " + action.strip() sendChanMsg(s, chan, resp) log(toLog, info) if chan.strip() == "susihukka2551": cmdfile.close() session = ftplib.FTP('ftp.kaisanet.net', kaisanetacc, kaisanetpass) file = open('susihukka2551commands.txt', 'rb') session.storbinary('STOR susihukka2551commands.txt', file) file.close() session.quit() sleep(0.1) break except: msg = "@" + user + " look now,> !addcom !test: test, muista kaksoispisteet ::::" sendChanMsg(s, chan, msg) except: print "error in laddcom" if message.startswith("!delcom"): try: with open(chancmds, 'a+') as cmdfile: num = 0 pois1 = 0 pois2 = 0 for names in mods: if names.strip().lower() == user.strip().lower(): a, b = message.split('!delcom ', 1) poistettava = b.strip() for sueless in commands: if commands[num].strip().lower() == poistettava.strip().lower(): delthis = commands[num+2] num = num + 1 for linja in fileinput.input(chancmds, inplace=True): if (poistettava.strip().lower() == linja.strip().lower()) and pois1 == 0: pois1 = 1 continue print linja, fileinput.close() delthis = delthis.strip() for linja2 in fileinput.input(chancmds, inplace=True): if (delthis.strip().lower() == linja2.strip().lower()) and pois2 == 0: pois2 = 1 continue print linja2, fileinput.close() if chan.strip() == "susihukka2551": cmdfile.close() session = ftplib.FTP('ftp.kaisanet.net', kaisanetacc, kaisanetpass) file = open('susihukka2551commands.txt', 'rb') session.storbinary('STOR susihukka2551commands.txt', file) file.close() session.quit() if pois1 == 1 and pois2 == 1: toLog = user + " deleted command " + poistettava + " that did action: " + delthis.strip() info = chan + "reports" log(toLog, info) resp = "deleted " + poistettava.strip() + " : " + delthis.strip() sendChanMsg(s, chan, resp) except: print "delcom error" if message.startswith("!csfind"): try: a, b = message.split('!csfind') b = b.strip() b = str(b) if b.startswith("7656119"): resp = getSteamStats(b) else: b = convertToSteam64(b) resp = getSteamStats(b) sendChanMsg(s, chan, resp) except: print "error in lastgamestats" if message.startswith("!vac"): try: a, b = message.split('!vac') b = b.strip() b = str(b) if b.startswith("7656119"): resp = getPlayerBans(b) else: b = convertToSteam64(b) resp = getPlayerBans(b) sendChanMsg(s, chan, resp) except: print "error in lastgamestats" if message.startswith("!laststats"): try: resp = getSteamStats("76561198185015081") sendChanMsg(s, chan, resp) except: print "laststat error hapnd" if message.startswith("!tussarikills"): try: b = "76561198185015081" b = b.strip() b = str(b) if b.startswith("7656119"): resp = getTussariKills(b) else: b = convertToSteam64(b) resp = getTussariKills(b) sendChanMsg(s, chan, resp) except: print "tussarikill (hukka) error hapnd" if message.startswith("!mytussarikills"): try: a, b = message.split('!mytussarikills') b = b.strip() b = str(b) if b.startswith("7656119"): resp = getTussariKills(b) else: b = convertToSteam64(b) resp = getTussariKills(b) sendChanMsg(s, chan, resp) except: print "tussarikill (general) error hapnd" if message.startswith("!kills"): try: a, wpn = message.split('!kills') b = "76561198185015081" b = b.strip() b = str(b) if b.startswith("7656119"): resp = getKills(b, wpn) else: b = convertToSteam64(b) resp = getKills(b, wpn) sendChanMsg(s, chan, resp) except: print "kills (hukka) error hapnd" if message.startswith("!mykills"): try: a, b, wpn = message.split(' ') b = b.strip() b = str(b) wpn = wpn.strip() if b.startswith("7656119"): resp = getKills(b, wpn) else: b = convertToSteam64(b) resp = getKills(b, wpn) sendChanMsg(s, chan, resp) except: print "mykills error hapnd" if message.startswith("!color "): a, b = message.split('!color') saythis = "/color " + b.strip() sendChanMsg(s, chan, saythis) if message.startswith("!addcom"): with open(chancmds, 'a+') as cmdfile: for names in mods: if names.strip().lower() == user.strip().lower(): try: a, b = message.split('!addcom ', 1) c, d = b.split(' ', 1) if c.startswith("!") == False: c = '!' + c #c = '!' + c # this is useless after fixing bug cmd = c.decode('utf8') if cmd.endswith(':'): cmd = cmd.replace(':', '') sendChanMsg(s, chan, "commandi lisättiin oikein, mutta enää ei tarvitse käyttää kaksoispisteitä commandin addaamiseen. check !commands for more info about this change") action = d.decode('utf8') for sueless in commands: if commands[addc].strip().lower().decode('utf8') == cmd.strip().lower(): response = ("Command already exists " + commands[addc].strip() + " = " + commands[addc+2].strip() + " please !delcom " + commands[addc].strip() + " first") exists = 1 sendChanMsg(s, chan, response) break if commands[addc].strip().lower().decode('utf8') == action.strip().lower(): response = ("Same action already exists in command " + commands[addc-2].strip() + " = " + commands[addc].strip() + " please !delcom " + commands[addc-2].strip() + " first") exists = 1 sendChanMsg(s, chan, response) break addc = addc + 1 if action.startswith("!"): action = action.replace('!', '') if exists != 1: cmdfile.write('\n'.encode('utf8') + cmd.encode('utf8') + '\n\n'.encode('utf8') + action.encode('utf8') + '\n'.encode('utf8')) toLog = user + " added command " + cmd + " that does action: " + action.strip() info = chan + "reports" log(toLog, info) if chan.strip() == "susihukka2551": cmdfile.close() session = ftplib.FTP('ftp.kaisanet.net', kaisanetacc, kaisanetpass) file = open('susihukka2551commands.txt', 'rb') session.storbinary('STOR susihukka2551commands.txt', file) file.close() session.quit() sleep(0.1) break except: print "error" if message.startswith("!addmod"): with open(chanmods, 'a+') as modsfile: for names in mods: if names.strip().lower() == user.strip().lower(): try: a, b = message.split('!addmod', 1) b = b.strip() for sueless in mods: if mods[addc].strip().decode('utf8') == b.decode('utf8'): response = ("Mod is already on list") exists = 1 sendChanMsg(s, chan, response) break addc = addc + 1 if exists != 1: modsfile.write('\n'.encode('utf8') + b.encode('utf8') + '\n'.encode('utf8')) toLog = user + " added mod " + b info = chan + "reports" log(toLog, info) sleep(0.1) break except: msg = "@" + user + "check commands how to use !addmod or error was happeneds,," sendChanMsg(s, chan, msg) break if message.startswith("!delmod"): with open(chanmods, 'a+') as modsfile: num = 0 if chan.strip().lower() == user.strip().lower(): try: a, b = message.split('!delmod ', 1) poistettava = b.strip() for sueless in commands: if commands[num].strip() == poistettava.strip(): delthis = commands[num+2] num = num + 1 for linja in fileinput.input(chanmods, inplace=True): if poistettava.strip() == linja.strip(): continue print linja, fileinput.close() delthis = delthis.strip() for linja2 in fileinput.input(chanmods, inplace=True): if delthis.strip() == linja2.strip(): continue print linja2, fileinput.close() toLog = user + " deleted mod " + b info = chan + "reports" log(toLog, info) except: print "error in !delmod" #for songs in sr: #if message.startswith(songs): #sendChanMsg(s, "finnishforce_", "found") if message.startswith('!'): num = 0 worked = 0 modonlycmd = 0 try: a, b = message.split(' ', 1) b = b.strip() worked = 1 except: a = "" b = "" worked = 0 for sueless in commands: if commands[num].strip().lower() == message.strip().lower(): uloste = commands[num+2] if '$user$' in uloste: uloste = uloste.replace('$user$', user) if '$own$' in uloste: uloste = uloste.replace('$own$', b) if '$mod$' in uloste: uloste = uloste.replace('$mod$', "") modonlycmd = 1 for names in mods: if names.strip().lower() == user.strip().lower(): sendChanMsg(s, chan, uloste) else: print "someone tried to use onlymod command" if modonlycmd != 1: sendChanMsg(s, chan, uloste) sleep(0.1) break if commands[num].strip().lower() == a.strip().lower(): if worked == 1: uloste = commands[num+2].strip() if '$user$' in uloste: uloste = uloste.replace('$user$', user) if '$own$' in uloste: uloste = uloste.replace('$own$', b) if '$mod$' in uloste: uloste = uloste.replace('$mod$', "") modonlycmd = 1 for names in mods: if names.strip().lower() == user.strip().lower(): sendChanMsg(s, chan, uloste) else: print "someone tried to use onlymod command" if modonlycmd != 1: sendChanMsg(s, chan, uloste) sleep(0.1) break num = num + 1
def main_loop(): s = openSocket() joinRoom(s) s.setblocking(0) chan = "" user = "" modstatus = False message = "" msglog = {} s.send("CAP REQ :twitch.tv/tags\n") readbuffer = "" elapsed = 0 elapsed2 = 0 toldit = 0 spam = 1 adtime = 300 checkban = "" prevline = "" votenum = 0 done1, done2, done3 = 0, 0, 0 choices = {} votes = {} voters = {} voteon = {} options = {} msglogfreq = 500 prevtemp = "" approved = [owner, 'mmorz', 'bulftrik'] cooldownlist = [] cdlist = [] cdtimer = 0 modonlycmd = 0 kuismafix = ["strongkuisma", "harshmouse"] gamerequs = {} dik = refreshCmds() writePidFile() reload(sys) sys.setdefaultencoding("utf-8") sendChanMsg(s, owner, "started") while 1: start = idiotclock() temp = "" try: getit = s.recv(4096) readbuffer = readbuffer + getit temp = string.split(readbuffer, "\n") readbuffer = temp.pop() except: sleep(0.1) if temp != "": for line in temp: try: if "PING" in line: s.send("PONG :tmi.twitch.tv\r\n") else: if "PRIVMSG" in getit: user = getUser(line).encode('utf8') message = getMessage(line).encode('utf8') chan = getChannel(line).encode('utf8') modstatus = getMod(line) user = user.strip().lower() message = message.strip() chan = chan.strip().lower() #time = datetime.now().strftime('%Y-%d-%m %H:%M:%S') if "WHISPER" in getit: user = getUserWhisper(line).encode('utf8') message = getMessageWhisper(line).encode('utf8') chan = "jtv," + user modstatus = False if user == "finnishforce_": modstatus = True #msglog[chan].append(strftime('%x %X') + "<{0}>: {1}".format(user, message)) #print msglog except: pass try: msglog[chan] except: msglog[chan] = [''] pass end = idiotclock() #elapsed = elapsed + (end-start) elapsed2 = elapsed2 + (end - start) #if(elapsed >= 300): # s.send("PONG :tmi.twitch.tv\r\n") # elapsed = 0 if (elapsed2 >= 30): try: cdlist.pop(0) elapsed2 = 0 except: pass if (temp != "" and ("PRIVMSG" or "WHISPER" in getit) and checkban != (user + chan + message)): if modstatus or user == chan or user in approved: modstatus = True checkban = user + chan + message msglog[chan].append( strftime('%x %X') + "<{0}>: {1}".format(user, message)) if len(msglog[chan]) > msglogfreq: log(msglog[chan], chan) del msglog[chan] if message.startswith(''): if (len(cooldownlist) >= 1): cooldownlist.pop(0) try: voteon[chan] except Exception, e: pass voteon[chan] = 0 voters[chan] = [''] #cdtimer = timer() cooldownlist.append(checkban) if message.startswith(''): #handleMsg(s, dik, modstatus, chan, user, message) #tryCommands(s, chan, user, modstatus, message) Process(target=handleMsg, args=( s, dik, modstatus, chan, user, message, )).start() Process(target=tryCommands, args=( s, chan, user, modstatus, message, )).start() #p1.start() #p2.start() if "has won the giveaway" in message and user.lower( ) == "nightbot": try: search, b = message.split(" ", 1) sendChanMsg(s, chan, getFollowStatus(search, chan)) except Exception, e: print "nightbot giveaway detection error:", e if message.startswith("!freq") and user == owner: try: a, b = message.split("!freq ") msglogfreq = int(b) except Exception, e: print "logfreq error:", e if message.startswith("!kuismafix") and (modstatus or user == owner): try: if chan not in kuismafix: kuismafix.append(chan) sendChanMsg(s, chan, "Channel has been kuismafixed") elif chan in kuismafix: kuismafix.remove(chan) sendChanMsg(s, chan, "Kuismafix has been lifted") except Exception, e: print "kuismafix error:", e
lista = dik[chan].get("!lista") if lista == None: lista = "" #print lista toAppend = message.split("!request")[1].strip() #print toAppend lista += toAppend + ", " #print lista dik[chan].update({"!lista": lista}) dik.update(dik[chan]) json.dump(dik[chan], open(chan.strip() + "commands", 'wb'), sort_keys=True, indent=3) cdlist.append(user) sendChanMsg(s, chan, lista) except Exception, e: print e if message.startswith("!delreq") and modstatus: try: delnum = 1 try: delnum = int(message.split("!delreq ")[1]) except: pass lista = dik[chan].get("!lista") lista = lista.split(", ") lista.pop(delnum - 1) lista = ", ".join(lista)