Пример #1
0
def run():
	s = openSocket()
	userListFile = open("userlist.txt", "w")
	joinRoom(s)
	readbuffer = ""

	while True:
		readbuffer = readbuffer + s.recv(1024).decode()
		temp = readbuffer.split("\n")
		readbuffer = temp.pop()
		
		for line in temp:
			print(line)
			if "PING" in line:
				s.send((line.replace("PING", "PONG")+ "\r\n").encode("utf-8"))
				break

			user = getUser(line)
			message = getMessage(line)
			print (user + " typed :" + message)

			#Greet New User
			if isUserNew(user):
				welcomeNewUser(s,user)
				users.append(user)
				userListFile.write(user + " ")
				print(users)
Пример #2
0
def youSuck(line, s):
    user = getUser(line.lower())
    message = getMessage(line.lower())

    resuck = [("No, you suck %s!" % user), ("You can suck a  duck %s!" % user)]

    if any(msg in message.split() for msg in suck):
        sendMessage(s, random.choice(resuck))
Пример #3
0
def ohHey(line, s):
    user = getUser(line.lower())
    message = getMessage(line.lower())

    rehey = [("Bruv sup %s!" % user), ("Nice to see you %s!" % user),
             ("How's are your day been %s?" % user), ("What's up %s?" % user)]

    if (any(msg in message.split() for msg in greetings)):
        sendMessage(s, random.choice(rehey))
Пример #4
0
def twitchBot():
    if app.isConnectionHealthy():
        readbuffer = app.recvBuff()
        if readbuffer:
            temp = string.split(readbuffer, "\n")
            readbuffer = temp.pop()
            for line in temp:
                if "PING" in line:
                    app.sendMessage()
                    break
                app.addToList(getUser(line), getMessage(line))

    app.after(1000, twitchBot)
Пример #5
0
def refreshMessages():
    from Initialize import users, currentUserIndex
    readbuffer = ""
    while True:
        readbuffer = readbuffer + users[currentUserIndex].recv(1024)
        temp = string.split(readbuffer, "\n")
        readbuffer = temp.pop()
            
        for line in temp:
            gui.displayMessage(line)
            user = getUser(line)
            message = getMessage(line)
            gui.displayMessage(user + " typed :" + message)
Пример #6
0
    def readChat(self):
        readbuffer = self.s.recv(1024)
        temp = string.split(readbuffer, "\n")
        readbuffer = temp.pop()

        for line in temp:
            print(line)
            if "PING" in line:
                self.s.send(line.replace("PING", "PONG"))
                break
            user = getUser(line)
            message = getMessage(line)
            print user + " typed :" + message
            return str(message), str(user)
Пример #7
0
def customRespond(line, s):
    user = getUser(line.lower())
    message = getMessage(line.lower())

    reply = [("%s beat me so bad AhhSooCrazy owes him money!" % user),
             ("%s really gave it to AhhSooCrazy. Giggity!!!" % user)]

    if (user == "its_chris19"):
        if (any(msg in message for msg in customre)):
            sendMessage(s, random.choice(reply))

    if (user == "jwilson3571"):
        if (any(msg in message for msg in customre)):
            sendMessage(s, random.choice(reply))
Пример #8
0
    readbuffer = temp.pop()

    # When a line appears, check if it's just a twitch automatic message
    for line in temp:
        testPing = checkPing(line)
        if len(testPing) != 0:
            if testPing == "PING ":
                print("PONG")
                s.send(bytes("PONG :tmi.twitch.tv", "UTF-8"))
                sendMessage(s, "YOU SHOULD NEVER SEE THIS MESSAGE IN CHAT!")
                line = "PING :[email protected] PRIVMSG #Twitch :PING "
            else:
                print("ERROR: checkPing returned " + testPing)
                
        # Extract the user and message from the line, print it out in terminal, update seconds
        user = getUser(line)
        message = getMessage(line)
        print(user + " said " + message)
        seconds = int(time.time() - time_start)

        # Reset the possible hangman answers so that the full master list is used again (CHANNEL ONLY)
        if user == getChannel() and message == "!addPokes":
            read = open("HangmanMasterList.txt", "r")
            add = open("Hangman.txt", "w")
            answer = read.readline()
            hangmanCatalog = {}
            while answer != "DONE\n":
                hangmanCatalog.update({answer:0})
                answer = read.readline()
            add.write(str(hangmanCatalog))
            print("Done!")
Пример #9
0
def chatBot(chan, newjoin):
    lasttip = datetime.datetime.now()
    s = openSocket(chan)
    joinRoom(s, chan, newjoin)
    readbuffer = ""
    close = False

    while close != True:
        lastping = datetime.datetime.now()
        readbuffer = readbuffer + s.recv(1024).decode("UTF-8")
        temp = str.split(readbuffer, "\n")
        readbuffer = temp.pop()
        js = open('users.txt')
        users = json.load(js)
        js.close()

        # User Settings Go Here
        caps = users[chan][0]

        if lasttip < datetime.datetime.now() - datetime.timedelta(hours=1):
            lasttip = datetime.datetime.now()
            commandFROGTip(s, chan, caps)

        for line in temp:
            print(line)
            # reply to IRC PING's so we dont get disconnected
            if "PING" in line:
                s.sendall(bytes("PONG :tmi.twitch.tv\r\n", "UTF-8"))
                lastping = datetime.datetime.now()
                break
            user = getUser(line)
            message = getMessage(line)
            print(user + " typed :" + message)
            #Listen for !frogtip command
            if re.search(r'^!frogtip', message, re.IGNORECASE):
                if lasttip < datetime.datetime.now() - datetime.timedelta(
                        seconds=15):
                    commandFROGTip(s, chan, caps)
                    lasttip = datetime.datetime.now()
                    break
            if re.search(r'^!join', message, re.IGNORECASE):
                print(chan)
                if chan == IDENT.lower():
                    if user not in users:
                        newjoin = True
                        users[user] = [0]
                        sendMessage(
                            s, chan, "Joining " + user +
                            "'s channel. If you would like FROGTips to hop off, type !leave in your channel while FROG is nearby."
                        )
                        joinChannel(user, newjoin)
                        with open('users.txt', 'w') as file:
                            file.write(json.dumps(users))
                            file.close
                    else:
                        sendMessage(
                            s, chan,
                            "FROGTips is already in this channel. Please do not hog FROG"
                        )
                    break
                else:
                    sendMessage(
                        s, chan,
                        "To have FROGTips join your channel, say !join in the chat at https://twitch.tv/frogtips"
                    )
                    break
                break
            if re.search(r'^!leave', message, re.IGNORECASE):
                if chan == user:
                    sendMessage(s, chan, "Leaving " + user + "'s channel. D:")
                    del users[user]
                    print(users)
                    with open('users.txt', 'w') as file:
                        file.write(json.dumps(users))
                        file.close
                    close = True
                else:
                    sendMessage(s, chan,
                                "Hop off, you aren't the channel owner.")
                break
            if re.search(r'^!caps', message, re.IGNORECASE):
                if chan == IDENT.lower():
                    sendMessage(s, chan,
                                "Toggling CAPS in " + user + "'s channel.")
                    print(users[user][0])
                    if users[user][0] == 1:
                        users[user][0] = 0
                        with open('users.txt', 'w') as file:
                            file.write(json.dumps(users))
                            file.close
                    else:
                        users[user][0] = 1
                        with open('users.txt', 'w') as file:
                            file.write(json.dumps(users))
                            file.close
                    break
                break
        time.sleep(0.2)
        if lastping < datetime.datetime.now() - datetime.timedelta(minutes=7):
            chatBot(chan, newjoin)
            close = True
        pass
Пример #10
0
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
Пример #11
0
        teamMessage += "VS. "
        for player in range(teamsize, teamsize * 2):
            teamMessage += players[player] + " "

        messageQueue.append(teamMessage)

    processMessageQueue()


while runServer:
    response = s.recv(1024).decode("utf-8")
    if response == "PING :tmi.twitch.tv\r\n":
        s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
    else:
        # print(response)
        user = getUser(response)
        message = getMessage(response)
        print(user + " typed: " + message)
        if "!enter" in message:
            if addUser(user):
                sendMessage(s, "{} entered".format(user))

        elif "!reset" in message and "cwittofur" in user:
            resetUsers()

        elif "!matchup" in message and "cwittofur" in user:
            if userCount() < 2:
                sendMessage(s, "Not enough entrants")
            else:
                shipTypeID = getShipTypeID(message)
                shipFactionID = getFactionID(message)
Пример #12
0
    def get_votes(self):

        try:
            chat_data = self.s.recv(1024)
        except socket.timeout:
            self.after(500, self.get_votes)
            return

        self.readbuffer = self.readbuffer + chat_data
        print "Reading successful"
        temp = self.readbuffer.split('\n')
        self.readbuffer = temp.pop(
        )  #save the last (possibly incomplete) line for later
        if self.readbuffer == "":
            pass  #no further messages in the queue

        for line in temp:
            print(line)

            if "PING" in line:
                s.send("PONG :tmi.twitch.tv\r\n".encode())
                break

            user = getUser(line)
            message = getMessage(line)

            print "{} typed: {}".format(user, message)

            if "!commands" in message:
                sendMessage(self.s, "'!voteA','!voteB','!voteC'")
                break

            if "!options" in message and user == CHANNEL:

                # Setting up the question/options to vote on
                # This is a bit of a work in progress

                theQuestion = message.split('? ', 1)[0] + "?"
                theQuestion2 = theQuestion.replace("!options", "")

                theOptions = message.split('? ', 1)[1]

                a = theOptions.split(' ', 4)[0]
                b = theOptions.split(' ', 4)[1]
                c = theOptions.split(' ', 4)[2]

                sendMessage(
                    self.s,
                    "Vote with: !" + str(a) + " !" + str(b) + " !" + str(c))

                self.questionUpdated = str(theQuestion2)
                self.optionA = str(a)
                self.optionB = str(b)
                self.optionC = str(c)

                # create empty options, needs a fix
                if "empty" in self.optionA:
                    self.optionA = " "

                self.voteAamount = 0
                self.voteBamount = 0
                self.voteCamount = 0

                self.alreadyVoted = []

                self.update_tekst()
                time.sleep(1)
                self.update()
                break

                #to do: Wrap if statements in separate functions
            if "!" + self.optionA in message and user != IDENT:
                self.voteAamount += 1
                print(self.voteAamount)
                self.update_tekst()
                time.sleep(1)
                self.update()
                break

            if "!" + self.optionB in message and user != IDENT:
                self.voteBamount += 1
                print(self.voteBamount)
                self.update_tekst()
                time.sleep(1)
                self.update()
                break

            if "!" + self.optionC in message and user != IDENT:
                self.voteCamount += 1
                print(self.voteCamount)
                self.update_tekst()
                time.sleep(1)
                self.update()
                break

            if "!reset" in message and user == CHANNEL:
                self.voteAamount = 0
                self.voteBamount = 0
                self.voteCamount = 0

                self.alreadyVoted = []

                self.update_tekst()
                time.sleep(1)
                self.update()

            if "!voteTest" in message and user not in self.alreadyVoted:
                self.voteTestAmount += 1
                self.alreadyVoted.append(user)
                break

            if "!exit" in message and user == CHANNEL:
                exit()

        self.update()
        self.after(500, self.get_votes)
Пример #13
0
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
Пример #14
0
 def processLine(self, line):
     self.addToList(getUser(line), getMessage(line))
Пример #15
-1
s = openSocket()
joinRoom(s)
readbuffer = ""

greeting = "hey, hi, hello, greetings"
person = "haylee, chat, friends, guys, all, everyone"
greeting = greeting.split(",")
person = person.split(",")
greeted = []
mods = []
trusted = []
wgreeted = open('Files/Greeted.txt', 'a')
tempWhitelist = []


while True:
	readbuffer = readbuffer + s.recv(1024)
        temp = string.split(readbuffer, "\n")
        readbuffer = temp.pop()
	for line in temp:
		#print("Debug: " + line)
                if "PING" in line:
                	s.send(line.replace("PING", "PONG"))
                        print(line)
                        print(line.replace("PING", "PONG"))
			sendMessage(s, "Debug: Ping found and responded too")
                        break
		user = getUser(line)
        	message = getMessage(line)
		chatCommands(readbuffer,s,message,temp,line,user,greeting,person,wgreeted,greeted,trusted,mods,tempWhitelist)