def toggle_sr(s, u, m):
    global sr_enabled
    if utils.isOp(u) or u.lower() == cfg.TWITCH_CHAN:
        if sr_enabled:
            sr_enabled = False
        else:
            sr_enabled = True
Example #2
0
def main():
    # Networking functions
    s = socket.socket()
    s.connect((cfg.HOST, cfg.PORT))
    s.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8"))
    s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8"))
    s.send("JOIN #{}\r\n".format(cfg.CHAN).encode("utf-8"))

    CHAT_MSG = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")
    utils.chat(s, "Hi everyone!")

    thread.start_new_thread(utils.threadFillOpList, ())

    while True:
        response = s.recv(1024).decode("utf-8")
        if response == "PINT :time.twitch.tv\r\n":
            s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
        else:
            username = re.search(r"\w+", response).group(0)
            message = CHAT_MSG.sub("", response)
            print(response)

            # Custom commands
            if message.strip() == "!time":
                utils.chat(s, "It is currently " + time.strftime("%I:%M %p %Z on %A, %B %d, %Y."))
            if message.strip() == "!messages" and utils.isOp(username):
                utils.chat(s, "Welcome to KBman99's Live Stream! Please follow below to see when I go live next!")
            if message.strip() == "!twitter":
                utils.chat(s, "My twitter is https://twitter.com/_the_kB")
        sleep(1)
Example #3
0
def toggle_sr(s, u, m):
    global sr_enabled
    if utils.isOp(u) or u.lower() == "cockeyedgaming":
        if sr_enabled:
            sr_enabled = False
        else:
            sr_enabled = True
Example #4
0
def main():
    s = socket.socket()
    s.connect((config.HOST, config.PORT))
    s.send("PASS {}\r\n".format(config.PASS).encode("utf-8"))
    s.send("NICK {}\r\n".format(config.NICK).encode("utf-8"))
    s.send("JOIN #{}\r\n".format(config.CHAN).encode("utf-8"))

    chat_message = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")
    utils.mess(s, "What is even up, dogs?")

    thread.start_new_thread(utils.fillOpList, ())
    while True:
        response = s.recv(1024).decode("utf-8")
        if response == "PING :tmi.twitch.tv\r\n":
            s.send("POND :tmi.twitch.tv\r\n".encode("utf-8"))
        else:
            username = re.search(r"\w+", response).group(0)
            message = chat_message.sub("", response)
            print(response)


            if message.strip() == "!time":
                utils.mess(s, "it's currently: " + time.strftime("%I:%M %p %Z on %A %B %d %Y"))
            if message.strip() == "!messages" and utils.isOp(username):
                utils.mess(s, "Do something awesome!")
                utils.mess(s, "Go to youtube.com/winderton and click the subscribe button there!")
        sleep(1)
def remove_death(s, u, m):
    global deaths
    if utils.isOp(
            u) or u.lower() == "cockeyedgaming" or u.lower() == "firezerg_":
        deaths -= 1 if deaths > 0 else 0
        utils.chat(s, u,
                   "JK JK , she saved it. Only " + ` deaths ` + " spills!")
def noscream(s, u, m):
    global num_screams
    if utils.isOp(u) or u.lower() == "cockeyedgaming" or u.lower(
    ) == "getcrunkfriday":
        num_screams -= 1
        utils.chat(
            s, u, "Nvm... that was just me. Ash has only screamed " +
            ` num_screams ` + " times now...")
def scream(s, u, m):
    global num_screams
    if utils.isOp(u) or u.lower() == "cockeyedgaming" or u.lower(
    ) == "getcrunkfriday":
        num_screams += 1
        utils.chat(
            s, u, "Ash just screamed like a little bitch. That's " +
            ` num_screams ` + " times now...")
def add_deaths(s, u, m):
    global deaths
    if utils.isOp(
            u) or u.lower() == "cockeyedgaming" or u.lower() == "firezerg_":
        deaths += 1
        utils.chat(
            s, u, "Ash has spilled her drink " + ` deaths ` +
            " times. What a clumsy bitch.")
Example #9
0
def main():
    # Networking functions
    engine = pyttsx.init()
    voices = engine.getProperty('voices')
    for voice in voices:
        print(voice)
        engine.setProperty(voice, voice.id)  # changes the voice
        engine.say('Ready')
    engine.say("I am regy")
    engine.runAndWait()
    s = socket.socket()
    s.connect((keys.HOST, keys.PORT))
    s.send("PASS {}\r\n".format(keys.PASS).encode("utf-8"))
    s.send("NICK {}\r\n".format(keys.NICK).encode("utf-8"))
    s.send("JOIN #{}\r\n".format(keys.chan).encode("utf-8"))

    CHAT_MSG = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")
    utils.chat(s, "All set up")

    thread.start_new_thread(utils.threadFillOplist, ())

    while True:
        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:
            username = re.search(r"\w+", response).group(0)
            message = CHAT_MSG.sub("", response)
            print response

            if message.strip() == "!time" and utils.isOp(username):
                utils.chat(
                    s, "It's currently " +
                    time.strftime("%I:%M %p %Z on %A, %B %d, %Y."))

            if "!say" in message.strip():
                engine.say(re.sub('!say ', '', message.strip()))
                engine.runAndWait()

            if message.strip() == "!help":
                utils.chat(s, "!say, !time")

            if message.strip() == "!help" and utils.isOp(username):
                utils.chat(s, "!say, !time, !ban, !timeout")
        sleep(1)
Example #10
0
def main():
    # Networking functions
    s = socket.socket()
    s.connect((cfg.HOST, cfg.PORT))
    s.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8"))
    s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8"))
    s.send("JOIN #{}\r\n".format(cfg.CHAN).encode("utf-8"))

    CHAT_MSG = re.compile(r"^:\w+!\w+@\w+.tmi\.twitch\.tv PRIVMSG #\w+ :")
    utils.chat(s, "Hi everyone!")

    _thread.start_new_thread(utils.threadFillOpList, ())

    while True:
        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:
            username = re.search(r"\w+", response).group(0)
            message = CHAT_MSG.sub("", response)
            print(response)

            # Custom commands
            if message.strip() == "!time":
                utils.chat(s, "It is currently " + time.strftime("%I:%M %p %Z on %A, %B %d, %Y."))
            if message.strip() == "Hello FantastiBot!":
                utils.chat(s, "Hello " + username + "!")
            if message.strip() == "!mods":
                modlist = []
                for i in cfg.oplist:
                    if cfg.oplist[i] == "mod":
                        modlist.append(i)
                if len(modlist) == 0:
                    utils.chat(s, "There are no moderators currently online.")
                elif len(modlist) == 1:
                    utils.chat(s, "Currently, " + modlist[0] + " is the only moderator online.")
                elif len(modlist) >= 2:
                    modString = ""
                    for i in range(len(modlist)):
                        if i == len(modlist)-1:
                            modString += modlist[i]
                        elif i == len(modlist)-2:
                            modString += modlist[i] + " and "
                        elif i < len(modlist)-2:
                            modString += modlist[i] + ", "
                    utils.chat(s, modString + " are currently moderating.")

            # Custom OP commands
            if utils.isOp(username):
                if message.strip() == "!messages":
                    utils.chat(s, "Please follow me, I don't bite.")
                    utils.chat(s, "I'm so lonely.")
                if message.strip().find("!timeout") != -1:
                    utils.timeout(s, message[9:])
        sleep(1)
def sync_request(username="******"):
    global download_queue
    import threading
    from dbutils import MusicDB
    if not utils.isOp(username):
        return
    print("Attempting to sync...")
    db_location = cfg.MUSIC_DB
    db = MusicDB(db_location)
    playlists_to_add, tracks_to_add, tracks_to_remove = musicutils.sync_playlists_to_db(
        db, cfg.YOUTUBE_PLAYLIST_CHANNEL)
    # Add playlists.
    # for p2a in playlists_to_add:
    #     download_queue.append({
    #         'thread': None,
    #         'request_type': 'sync_add_playlist',
    #         'playlist_id': p2a[0],
    #         'playlist_name': p2a[1]
    #     })
    # Submit downloads for tracks.
    if len(tracks_to_add) > 0:
        download_thread = threading.Thread(
            target=utils.download_song_requests,
            args=[[
                "https://www.youtube.com/watch?v=" + t2a.youtube_id_
                for t2a in tracks_to_add
            ]])
        download_thread.start()
        download_queue.append({
            'thread': download_thread,
            'request_type': 'sync_add_tracks',
            'tracks': tracks_to_add
        })

    if len(tracks_to_remove) > 0:
        # Remove tracks from DB
        download_queue.append({
            'thread': None,
            'request_type': 'sync_remove_tracks',
            'tracks': tracks_to_remove
        })
Example #12
0
def main():
    # Networking functions
    s = socket.socket()
    s.connect((cfg.HOST, cfg.PORT))
    s.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8"))
    s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8"))
    s.send("JOIN #{}\r\n".format(cfg.CHAN).encode("utf-8"))

    CHAT_MSG = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")
    utils.chat(s, "Hi everyone!")

    thread.start_new_thread(utils.threadFillOpList, ())

    commands = sql.getCommands()

    cmd = []
    for c in commands:
        cmd.append(Command(c["Command"], c["Response"], c["Description"], c["Op"]))

    while True:
        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:
            username = re.search(r"\w+", response).group(0)
            message = CHAT_MSG.sub("", response)
            print(response)

            for c in cmd:
                if message.strip() == c.cmd:
                    if c.op == 0:
                        parse(c, s)
                    else:
                        if utils.isOp(username):
                            parse(c, s)
        sleep(1)
    utils.chat(s, "Bye everyone :)");
Example #13
0
def startChatBot(chan):
    print('Chat bot starting')
    s = socket.socket()
    getConnection(s, chan)

    print("Bot started")
    timecount = time.time()
    thread.start_new_thread(utils.fillOpList, (chan, ))
    while True:
        if time.time() - timecount >= 25 * 60:
            utils.mess(
                s, chan, 'MEMES AND announcements =>'.upper() +
                'https://discord.gg/UnUhDNz <=')
            timecount = time.time()

        # try:
        rawResponse = s.recv(1024).decode('utf-8')
        # except ConnectionResetError:
        #    getConnection(s)
        # print('===== Start of rawResponse =====\n', rawResponse, end='===== End of rawResponse =====\n')

        if str(rawResponse)[0:19] in 'PING :tmi.twitch.tv':
            s.send("PONG :tmi.twitch.tv\r\n".encode('utf-8'))
        elif str(rawResponse).__contains__("Login unsuccessful"):
            utils.refreshToken(getUser(chan))
            s.close()
            s = socket.socket()
            getConnection(s, chan)
        else:
            try:
                username = str(rawResponse).split('!')[0][1:]
                message = str(rawResponse).split('#%s :' % chan)[-1].strip()
                print(time.strftime("%H:%M:%S") + ' "%s":' % username, sep='')
                print('"%s"' % message,
                      sep='',
                      end='\n=====================================\n')
            except Exception as x:
                print(
                    '==achtung==achtung==achtung==achtung==achtung==achtung==achtung=='
                    .upper())
                print('===== Exeption start =====')
                print(x, x.args)
                print('===== Exeption  end =====')
                print('===== Response start =====')
                print(rawResponse, end='')
                print('===== Response end =====')
                print('===== Username =====')
                print(username)
                print('===== Username =====')
                print(
                    '==achtung==achtung==achtung==achtung==achtung==achtung==achtung=='
                    .upper())

            if message == '!discord':
                utils.mess(s, chan, "=>https://discord.gg/UnUhDNz<=")
            if message.strip() == "!test" and utils.isOp(username):
                utils.mess(s, chan, "test?")
            if ('bigfollows' in message.lower()) and ('com'
                                                      in message.lower()):
                reason = 'Advertising'
                utils.ban(s, chan, username, reason)
                print('User: "******" was banned for the "%s"' %
                      (username, reason),
                      end='\n=====================================\n')

        time.sleep(1)
Example #14
0
def main():
    #print("hello")
    #Networking things
    s = socket.socket()
    s.connect((cfg.HOST, cfg.PORT))
    s.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8"))
    s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8"))
    s.send("JOIN #{}\r\n".format(cfg.CHAN).encode("utf-8"))

    CHAT_MSG = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")
    utils.chat(s, "Hi everyone!")

    thread.start_new_thread(utils.threatFillOpList, ())
    #thread.start_new_thread(utils.constantGreeting(s), ()) #look into multiprocessing / multithreading (threding library?)

    timeCount = 0
    while True:
        try:
            response = s.recv(1024)
            #if the connection to tmi.twitch.tv connects will get a pong
            if not response: break
            r = response.decode("utf-8")
            if r == "PING :tmi.twitch.tv\r\n":
                s.send("PONG :tmi.twtich.tv\r\n".encode("utf-8"))
            else:
                username = re.search(r"\w+", r).group(0)
                message = CHAT_MSG.sub("", r)
                print(r)
                timeCount += 1

                # Multithreading for all the greeting
                # Hope this works and doesn't break
                #t = threading.Thread(target=utils.constantGreeting(s))
                #t.daemon = True
                #t.start()

                # Custom Commands

                #Not a real timer sadly, This will increment each time a command is issued.
                if timeCount == 500:
                    utils.chat(
                        s,
                        "Masc4Masc Mondays: Solo Stream with Jason! 8PM EST until 11P/12AM"
                    )
                    utils.chat(
                        s,
                        "Tabby Tuesdays: Solo Stream with Trent! 8PM EST until 11P/12AM"
                    )
                    utils.chat(
                        s,
                        "Thirsty Thursdays: Solo Stream with Matt! 10PM EST until 12AM"
                    )
                    utils.chat(
                        s,
                        "Festive Friday: Join the entire crew for party games! 7:30PM EST (ish) until we go to the bar (12A/1A)"
                    )
                    utils.chat(
                        s,
                        "Shady Saturday: Come talk shit and spill the T! 2PM EST until 8PM EST. WOOF!"
                    )
                    timecCount = 0
                #if timeCount == 1000:
                #    utils.chat(s, "Remeber to follow and turn on the notification settings to know when we go on. To get more information about us, see the details portion of the stream.")
                #    timeCount = 0
                print utils.isOp(username)
                if message.strip() == "!schedule" and utils.isOp(
                        username) and cfg.CHAN == "supercubs":
                    utils.chat(
                        s,
                        "Masc4Masc Mondays: Solo Stream with Jason! 8PM EST until 11P/12AM"
                    )
                    utils.chat(
                        s,
                        "Tabby Tuesdays: Solo Stream with Trent! 8PM EST until 11P/12AM"
                    )
                    utils.chat(
                        s,
                        "Thirsty Thursdays: Solo Stream with Matt! 10PM EST until 12AM"
                    )
                    utils.chat(
                        s,
                        "Festive Friday: Join the entire crew for party games! 7:30PM EST (ish) until we go to the bar (12A/1A)"
                    )
                    utils.chat(
                        s,
                        "Shady Saturday Come talk shit and spill the T! 2PM EST (ish) until 8PM EST. WOOooF!"
                    )

                #!commands whispers the command list NOT WORKING! -- needs a seperate connection to Group chat :/ Not sure..
                if message.split()[0] == "!commands" and utils.isOp(username):
                    utils.whisper(s,
                                  message.split(' ', 2)[1],
                                  message.split(' ', 2)[2])
                #!ban Hammer
                if message.split()[0] == "!ban" and utils.isOp(username):
                    user = message.split()[1]
                    try:
                        utils.ban(s, message.split()[1])
                    except:
                        utils.chat(s, "No name")
                #!timeout
                if message.split()[0] == "!timeout" and utils.isOp(username):
                    user = message.split()[1]
                    try:
                        utils.timeout(s, message.split()[1])
                    except:
                        utils.chat(s, "No name")
                #!eliminate <name>
                if message.split()[0] == "!eliminate":
                    utils.eliminate(s, message.split()[1], username)
                #!eliminated <name>
                if message.split()[0] == "!eliminated" and utils.isOp(
                        username):
                    utils.eliminated(s, message.split()[1])
                #!game (In testing)
                if message.strip() == "!game":
                    #if len(message.strip()) > 1: #get requests package installed
                    #   utils.chat(s, utils.currentPlaying())
                    utils.showGame(s)
                #!create Command
                if message.split()[0] == "!create" and utils.isOp(
                        username
                ):  # I could make this safer by checking of the word has ! before the command else add it.
                    utils.createCommands(
                        message.split(' ', 2)[1],
                        message.split(' ', 2)[2])
                #!useCommands created
                if unicode(message.strip()) in cfg.commands:
                    utils.useCommands(s, message.strip())
                #!delete commands
                if message.split()[0] == "!delete" and utils.isOp(username):
                    utils.removeCommands(message.split()[1])
                #!uptime
                if message.strip() == "!uptime":
                    then = datetime.now()
                    utils.chat(
                        s, cfg.CHAN + " have been on for: " + (then - start))
                #!valentine
                if message.split()[0] == "!valentine":
                    utils.valentine(s, message.split(' ', 1)[1], username)
                #!total
                if message.strip() == "!total":
                    utils.total(s)
                #!switch
                if message.strip() == "!switch" and utils.isOp(username):
                    utils.chat(
                        s,
                        "Come join us at midinght release of the switch on March 3rd. We will be streaming for the release of the switch, more info to come!!!"
                    )

                #if message.strip() == "!points":
                #   utils.points(s, username + " points are " + utils.points(username))
                #if message.strip() == "!mods":
                #   print cfg.oplist
                #   if utils.isOp(username):
                #        utils.chat(s, username + " is a mod or higher")

        except:
            print "Main broke!"
        sleep(1)
Example #15
0
def token_recognition(token, digitDFA, charDFA, stringDFA, commentDFA, o_H_DFA,
                      line_number, character_table, token_l, error_l):
    #关键字和标识符
    if isAlpha(token[0]):
        if token in keywords:
            # print(token + "\t<关键字\t" + token + ">\t" + str(line_number))
            # if token + "\t关键字\t" + token + "\t" + str(line_number) not in token_l:
            token_l.append(token + "\t关键字\t" + token + "\t" + str(line_number))
        else:
            if token not in character_table:
                character_table.append(token)
                # print(token + "\t<标识符\t" + token + ">\t" + str(line_number))
                if token + "\t标识符\t" + token + "\t" + str(
                        line_number) not in token_l:
                    token_l.append(token + "\t标识符\t" + token + "\t" +
                                   str(line_number))

    if isOp(token[0]):
        # print(token + "\t<运算符\t" + token + ">\t" + str(line_number))
        #if token + "\t运算符\t" + token + "\t" + str(line_number) not in token_l:
        token_l.append(token + "\t运算符\t" + token + "\t" + str(line_number))

    if isDigit(token[0]):
        digitDFA_result, isfloat = digitDFA.in_digitDFA(token)
        if digitDFA_result:
            if isfloat:
                # print(token + "\t<浮点型常量\t" + token + ">\t" + str(line_number))
                #if token + "\t浮点型常量\t" + token + "\t" + str(line_number) not in token_l:
                token_l.append(token + "\t浮点型常量\t" + token + "\t" +
                               str(line_number))
            else:
                # print(token + "\t整形常量\t" + token + "\t" + str(line_number))
                #if token + "\t整形常量\t" + token + "\t" + str(line_number) not in token_l:
                token_l.append(token + "\t整形常量\t" + token + "\t" +
                               str(line_number))

        o_H_DFA_result, error_message, is_octal = o_H_DFA.in_O_H_DFA(token)
        if o_H_DFA_result:
            if is_octal:
                # print(token + "\t<八进制常量\t" + token+ ">\t" + str(line_number))
                #if token + "\t八进制常量\t" + token+ "\t" + str(line_number) not in token_l:
                token_l.append(token + "\t八进制常量\t" + token + "\t" +
                               str(line_number))
            else:
                # print(token + "\t<十六进制常量\t" + token + ">\t" + str(line_number))
                #if token + "\t十六进制常量\t" + token + "\t" + str(line_number) not in token_l:
                token_l.append(token + "\t十六进制常量\t" + token + "\t" +
                               str(line_number))

        if not digitDFA_result and not o_H_DFA_result:
            # print("错误:在" + str(line_number) + "行, 试图将" + token + "解析为数字型常量发生错误!")
            #if "错误:在" + str(line_number) + "行, 试图将" + token + "解析为数字型常量发生错误!" not in error_l:
            error_l.append("错误:在" + str(line_number) + "行, 试图将" + token +
                           "解析为数字型常量发生错误!")

    if isChar(token[0]):
        charDFA_result, error_message = charDFA.in_charDFA(token)

        if charDFA_result:
            # print(token + "\t<字符型常量\t" + token + ">\t" + str(line_number))
            #if token + "\t字符型常量\t" + token + "\t" + str(line_number) not in error_l:
            token_l.append(token + "\t字符型常量\t" + token + "\t" +
                           str(line_number))
        else:
            # print("错误:在" + str(line_number) + "行, 试图将" + token + "解析为字符型常量发生错误!" )
            #if "错误:在" + str(line_number) + "行, 试图将" + token + "解析为字符型常量发生错误!" not in error_l:
            error_l.append("错误:在" + str(line_number) + "行, 试图将" + token +
                           "解析为字符型常量发生错误!")

    if isString(token[0]):
        stringDFA_result, error_message = stringDFA.in_stringDFA(token)

        if stringDFA_result:
            # print(token + "\t<字符串常量\t" + token + ">\t" + str(line_number))
            #if token + "\t字符串常量\t" + token + "\t" + str(line_number) not in token_l:
            token_l.append(token + "\t字符串常量\t" + token + "\t" +
                           str(line_number))
        else:
            # print("错误:在" + str(line_number) + "行, 试图将" + token + "解析为字符串常量发生错误!")

            #if "错误:在" + str(line_number) + "行, 试图将" + token + "解析为字符型常量发生错误!" not in error_l:
            error_l.append("错误:在" + str(line_number) + "行, 试图将" + token +
                           "解析为字符型常量发生错误!")

    return character_table, token_l, error_l
Example #16
0
def handle_PRIVMSG(irc, args):
    nick = args.sender.nick
    ident = args.sender.ident
    address = args.sender.mask
    ignored = False
    try:
        chan, message = args.args
    except ValueError:
        return

    if chan == irc.nick:
        chan = nick

    for user in irc.ignored:
        if fnmatch.fnmatch(nick.lower(), user.lower()) == True:
            ignored = True
        elif fnmatch.fnmatch(address.lower(), user.lower()) == True:
            ignored = True
        elif chan.lower() == user.lower():
            ignored = True

    if isAdmin(irc, args.sender) or isOp(irc, args.sender):
        ignored = False

    if ignored == False:

        if "\x01ACTION " in message:
            _format = "* {nick} {message}".format(nick=nick,
                                                  message=message.replace(
                                                      "\x01ACTION ",
                                                      "").replace("\x01", ""))
        else:
            _format = "<{nick}> {message}".format(nick=nick, message=message)

        try:
            if len(irc.channels[chan]["buffer"]) > irc.buffermaxlen:
                irc.channels[chan]["buffer"].pop(0)
            irc.channels[chan]["buffer"].append(_format)
        except:
            # buffer doesn't exist? usually a pm
            pass
            #irc.channels[chan] = {"buffer": []}

        for cmd in bot_regexes.items():
            regex, func = cmd
            m = regex.search(message)
            if m:
                #log.info("(%s) Calling regex for %s", irc.netname, func.__name__)
                c = threading.Thread(target=func,
                                     args=(irc, args.sender, chan, m.groups()))
                c.daemon = True
                c.start()

        if args.args[0] == irc.nick:
            # in a pm, should reply to nick not self
            args.args[0] = nick
            regex = u"(?:{}?)(.*?)(?:$|\s+)(.*)".format(irc.prefix)
        else:
            regex = u"(?:{})(.*?)(?:$|\s+)(.*)".format(irc.prefix)
        m = re.match(regex, message)
        if m:
            command, cmdargs = m.groups()

            if chan in irc.conf["blacklisted_commands"]:
                if command in irc.conf["blacklisted_commands"][chan]:
                    return

            try:
                func = utils.bot_commands[command]
            except KeyError:
                pass

            else:
                try:
                    log.info("(%s) Calling command %r", irc.netname, command)
                    threading.Thread(target=func,
                                     args=(irc, args.sender, chan,
                                           cmdargs)).start()

                except Exception as e:
                    log.exception(
                        "(%s) Unhandled exception caught in command %r",
                        irc.netname, command)
                    irc.msg(chan, "Uncaught exception: {}".format(str(e)))

        if chan not in irc.conf.get("donotlog", []):
            try:
                if chan != irc.nick:
                    irc.nicks[nick]["lastaction"] = {
                        "action": "PRIVMSG",
                        "args": message,
                        "time": time.time(),
                        "chan": chan
                    }
            except:
                pass
def add_legendary(s, u, m):
    global legendaries
    if utils.isOp(u) or u.lower() == cfg.TWITCH_CHAN:
        legendaries.append(m)
        utils.chat(s, u, m + " added to legendaries!")
Example #18
0
def main():
    # Load framedata from csv
    df = pd.read_csv('fdata.csv')
    chars = set(df['Character'].values)
    swap = {
        ' ': '',
        ',': '',
        '/': '',
        'd+': 'd',
        'f+': 'f',
        'u+': 'u',
        'b+': 'b',
        'n+': 'n',
        'ws+': 'ws',
        'fc+': 'fc',
        'cd+': 'cd',
        'wr+': 'wr',
        'ra+': 'ra',
        'rd+': 'rd',
        'ss+': 'ss',
        '(': '',
        ')': ''
    }
    # Networking functions
    s = socket.socket()
    s.connect((cfg.HOST, cfg.PORT))
    s.send('PASS {}\r\n'.format(cfg.PASS).encode('utf-8'))
    s.send('NICK {}\r\n'.format(cfg.NICK).encode('utf-8'))
    for i in range(len(cfg.CHAN)):
        s.send('JOIN #{}\r\n'.format(cfg.CHAN[i]).encode('utf-8'))

    chat_msg = re.compile(r'^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :')
    for i in range(len(cfg.CHAN)):
        utils.chat(
            s,
            "Hi everyone! This is a CIS T7 framedata bot. !help for a list of commands.",
            cfg.CHAN[i])
    uptime = time.time()
    _thread.start_new_thread(utils.threadFillOpList, ())

    while True:
        response = s.recv(1024).decode('utf-8')
        try:
            channel = response.split('#')[1].split(' ')[0]
        except Exception as e:
            channel = ''
        if response == 'PING :tmi.twitch.tv\r\n':
            s.send("PONG :tmi.twitch.tv\r\n".encode('utf-8'))
        else:
            username = re.search(r'\w+', response).group(0)
            message = chat_msg.sub('', response)
            #print(response)

            # --------------------------CUSTOM COMMANDS--------------------------
            ms = message.strip()
            #print(ms)
            if ms == '!help':
                utils.chat(s, 'List of commands - pastebin.com/cra4fLgQ',
                           channel)

            if ms == '!info':
                utils.chat(
                    s,
                    'CIS T7 for framedata and more! Made by eatsports - twitch.tv/mousewell/ '
                    'I\'m renting a server to keep this bot running, '
                    'if you like this bot, please consider donating at my twitch page!',
                    channel)

            if ms == '!characters':
                utils.chat(
                    s, 'List of characters - ' + ' '.join(sorted(chars)) +
                    ' (!%character% %move% to get frame data)', channel)

            # --------------------------FRAMEDATA--------------------------
            if ms.startswith('!') and len(ms) > 1 and ms[1:].split(' ')[0][0].isalpha() \
                    and not ms.startswith('!sr') and not ms.startswith('!song') and not ms.startswith('!device')\
                    and not ms.startswith('!chars'):
                msg = ms[1:]
                name = msg.split(' ')[0].lower()
                if len(msg.split(' ')) > 1:
                    full_notation = msg.split(name[-2:] + ' ')[1]
                    notation = full_notation.lower()
                    for i, j in swap.items():
                        notation = notation.replace(i, j)
                else:
                    full_notation = ''
                    notation = ''

                if name in [
                        item for sublist in list(chd.CHAR_NAMES.values())
                        for item in sublist
                ]:
                    for key, val in chd.CHAR_NAMES.items():
                        if name in val:
                            name = key

                elif ''.join(msg.split(' ')[:2]).lower() \
                        in [item for sublist in list(chd.CHAR_NAMES.values()) for item in sublist]:
                    name = ''.join(msg.split(' ')[:2]).lower()
                    for key, val in chd.CHAR_NAMES.items():
                        if name in val:
                            full_notation = msg.split(name[-2:] + ' ')[1]
                            notation = full_notation.lower()
                            for i, j in swap.items():
                                notation = notation.replace(i, j)
                            name = key

                try:
                    m = df.loc[(df['Character'] == name)
                               & (df['Command'] == notation)].values[0]
                    for i in range(len(m)):
                        if pd.isnull(m[i]):
                            m[i] = '-'

                    output = 'Hit Level: {} ' \
                             'Startup: {} ' \
                             'On Block: {} ' \
                             'On Hit: {} ' \
                             'On CH: {} ' \
                             'Damage: {} ' \
                             'Notes: {}'.format(m[2], m[4], m[5], m[6], m[7], m[3], m[8])
                    utils.chat(s, output, channel)
                except Exception as e:
                    if name not in chars:
                        guess_c = difflib.get_close_matches(name.capitalize(),
                                                            chars,
                                                            n=2,
                                                            cutoff=0.6)
                        utils.chat(s, 'Character not found: {}.'.format(name),
                                   channel)
                        if guess_c:
                            utils.chat(
                                s, 'Maybe you meant this character(s)?: '
                                '{}'.format(', '.join(guess_c)), channel)
                    else:
                        try:
                            moves = df.loc[df['Character'] ==
                                           name]['Notation'].values
                            guess_m = difflib.get_close_matches(full_notation,
                                                                moves,
                                                                n=5,
                                                                cutoff=0.5)
                            utils.chat(
                                s, 'Move not found for {}: {}.'.format(
                                    name, full_notation), channel)
                            if guess_m:
                                utils.chat(
                                    s, 'Maybe you meant: {}'.format(
                                        '; '.join(guess_m)), channel)
                            else:
                                moves = df.loc[df['Character'] ==
                                               name]['Command'].values
                                guess_m = difflib.get_close_matches(notation,
                                                                    moves,
                                                                    n=5,
                                                                    cutoff=0.5)
                                if guess_m:
                                    utils.chat(
                                        s, 'Maybe you meant: {}'.format(
                                            ' or '.join(guess_m)), channel)
                        except Exception as e:
                            print(e)

            if ms == '!uptime':
                diff = time.time() - uptime
                utils.chat(
                    s, 'Went live {}h {}m ago.'.format(
                        str(diff / 3600)[:1],
                        str(diff / 60)[:1]), channel)

            if ms == '!time':
                utils.chat(
                    s, 'It is currently ' +
                    time.strftime('%I:%M %p %Z on %A, %B %d, %Y.'), channel)

            if ms == '!messages' and utils.isOp(username):
                utils.chat(s, "Please give me a follow at twitch.tv/mousewell",
                           channel)
                utils.chat(s, "Go to twitter.com/mousewell1 for my Twitter",
                           channel)
        sleep(1)
Example #19
0
def handle_PRIVMSG(irc, args):
    nick = args.sender.nick
    ident = args.sender.ident
    address = args.sender.mask
    ignored = False
    try:
        chan, message = args.args
    except ValueError:
        return

    if chan == irc.nick:
        chan = nick

    for user in irc.ignored:
        if fnmatch.fnmatch(nick.lower(), user.lower()) == True:
            ignored = True
        elif fnmatch.fnmatch(address.lower(), user.lower()) == True:
            ignored = True
        elif chan.lower() == user.lower():
            ignored = True

    if isAdmin(irc, args.sender) or isOp(irc, args.sender):
        ignored = False

    if ignored == False:

        if "\x01ACTION " in message:
            _format = "* {nick} {message}".format(nick=nick, message=message.replace("\x01ACTION ","").replace("\x01", ""))
        else:
            _format = "<{nick}> {message}".format(nick=nick, message=message)

        try:
            if len(irc.channels[chan]["buffer"]) > irc.buffermaxlen:
                irc.channels[chan]["buffer"].pop(0)
            irc.channels[chan]["buffer"].append(_format)
        except:
            # buffer doesn't exist? usually a pm
            pass
            #irc.channels[chan] = {"buffer": []}

        for cmd in bot_regexes.items():
            regex, func = cmd
            m = regex.search(message)
            if m:
                #log.info("(%s) Calling regex for %s", irc.netname, func.__name__)
                c = threading.Thread(target=func, args=(irc, args.sender, chan, m.groups()))
                c.daemon = True
                c.start()

        if args.args[0] == irc.nick:
            # in a pm, should reply to nick not self
            args.args[0] = nick
            regex = u"(?:{}?)(.*?)(?:$|\s+)(.*)".format(irc.prefix)
        else:
            regex = u"(?:{})(.*?)(?:$|\s+)(.*)".format(irc.prefix)
        m = re.match(regex, message)
        if m:
            command, cmdargs = m.groups()

            if chan in irc.conf["blacklisted_commands"]:
                if command in irc.conf["blacklisted_commands"][chan]:
                    return

            try:
                func = utils.bot_commands[command]
            except KeyError:
                pass

            else:
                try:
                    log.info("(%s) Calling command %r", irc.netname, command)
                    threading.Thread(target=func, args=(irc, args.sender, chan, cmdargs)).start()

                except Exception as e:
                    log.exception("(%s) Unhandled exception caught in command %r", irc.netname, command)
                    irc.msg(chan, "Uncaught exception: {}".format(str(e)))

        if chan not in irc.conf.get("donotlog", []):
            try:
                if chan != irc.nick:
                    irc.nicks[nick]["lastaction"] = {"action": "PRIVMSG", "args": message, "time": time.time(), "chan": chan}
            except:
                pass
Example #20
0
def main():
    if config.NICK == "":
        config.NICK = input("Enter bot's nick: ")
    if config.PASS == "":
        config.PASS = input("Enter bot's chat token: ")
    print("Would you like to change target channel? (y/n)")
    sym = input()
    if sym == 'y':
        config.CHAN = input("Enter channel name: ")
    s = socket.socket()
    s.connect((config.HOST, config.PORT))
    s.send("PASS {}\r\n".format(config.PASS).encode("utf-8"))
    s.send("NICK {}\r\n".format(config.NICK).encode("utf-8"))
    s.send("JOIN #{}\r\n".format(config.CHAN).encode("utf-8"))
    chat_message = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")

    utils.msg(s, "Daddy here!")

    _thread.start_new_thread(utils.fillUpOps, ())

    count = 0
    while True:
        response = s.recv(1024).decode("utf-8")
        if response == "PING :tmi.twitch.com\r\n":
            s.send("POND :tmi.twitch.com\r\n".encode("utf-8"))
        else:
            username = re.search(r"\w+", response).group(0)
            message = chat_message.sub("", response)
            print(response)
            print(message)
            # print(message.strip() == "!timeout excorex 30")
            if message.strip() == "!help":
                utils.msg(s, "Available chat commands:")
                utils.msg(s, "!time - Shows current time")
                utils.msg(s, "!oplist - Shows online ops")
                utils.msg(s, "!promote - ...")
                utils.msg(s, "!chatters - Shows current chatters' list")
                utils.msg(s, "!to <nick> <time in secs> - timeout some user(only for mods)")
            if message.strip() == "!time":
                utils.msg(s, "It's currently " + time.strftime("%H:%M on %A %B %d %Y"))

            if message.strip() == "!oplist":
                utils.msg(s, "Op list: ")
                for e in config.oplist:
                    utils.msg(s, "{}: {}".format(e, config.oplist[e]))

            if message.strip() == "!promote":
                utils.msg(s, "Dota 2 = #####")
                utils.msg(s, "eXCore = царь")

            if re.fullmatch(r"!to \w+ \d+", message.strip()) and utils.isOp(username):
                name = re.search(r" (\w+) ", message.strip()).group(1)
                totime = re.search(r" (\d+)$", message.strip()).group(1)
                utils.timeout(s, name, totime)
                utils.msg(s, name + " is timeouted for " + totime + " seconds")

            if message.strip() == "!chatters":
                url = "http://tmi.twitch.tv/group/user/excorex/chatters"
                req = urllib.request.Request(url)
                req.add_header("accept", "*/*")
                res = urllib.request.urlopen(req).read().decode("utf-8")
                if res.find("502 bad gateway") == -1:
                    data = json.loads(res)
                    for e in data["chatters"]:
                        for c in data["chatters"][e]:
                            mas = "{} : {}".format(c, e)
                            utils.msg(s, mas[:-1])
                    utils.msg(s, "Total chatters: {}".format(data["chatter_count"]))
            #if re.fullmatch(r"^!sendpm \w+ .*", message.strip()):                 ##Not Working
            #    name = re.search(r"!sendpm (\w+) ", message.strip()).group(1)
            #    mess = re.search(r"!sendpm \w+ (.*)", message.strip()).group(1)
            #    utils.pm(s, name, mess)
        count+=1
        if DEBUG_MODE and count > 1:
            cmd = input()
            s.send(cmd.encode("utf-8"))
        sleep(1)