Ejemplo n.º 1
0
def __main__():
    colors = [F.GREEN, F.YELLOW, F.BLUE, F.MAGENTA, F.CYAN]
    super_users = {'slewis':'U029RFUDH'}
    username = '******' #username for the bot
    token = os.getenv('stoken')
    dats_the_sound_of_da_police = False # enables police bot for @channels or @groups
    kill_me = False
    old_minute = 1000

    con = mdb.connect('localhost', os.getenv('dbuser1'), os.getenv('dbpass1'), 'rtm',
                      cursorclass=MySQLdb.cursors.DictCursor)
    cur = con.cursor()
    con2 = mdb.connect('localhost', os.getenv('dbuser2'), os.getenv('dbpass2'), 'rtm',
                      cursorclass=MySQLdb.cursors.DictCursor)
    cr = con2.cursor()

    print "Connecting"
    open_connection = rs.renew(token)
    if 'hello' in rs.to_u(open_connection.recv()):
        print 'Successfully Connected'
        open_connection.recv()
    icolor = 0
    while kill_me == False:
        try:
            # make sure we're connected to the db
            try:
                cur.fetchone()
                cr.fetchone()
            except:
                con = mdb.connect('localhost', os.getenv('dbuser1'), os.getenv('dbpass1'), 'rtm', cursorclass=mdb.cursors.DictCursor)
                cur = con.cursor()
                con2 = mdb.connect('localhost', os.getenv('dbuser2'), os.getenv('dbpass2'), 'rtm',
                                  cursorclass=MySQLdb.cursors.DictCursor)
                cr = con2.cursor()

            rightnow = datetime.datetime.now()
            hour = rightnow.hour
            minute = rightnow.minute
            is_weekday = 'True' if rightnow.isoweekday() < 6 else 'False'
            if old_minute != minute:
                sql = "SELECT * FROM Tasks WHERE (HOUR = %s OR HOUR = 247) AND Min = %s"
                query = cur.execute(sql, (hour, minute))
                if query > 0:
                    rows = cur.fetchall()
                    for row in rows:
                        if row["Weekday"] == is_weekday or row["Weekday"] == "All":
                            try:
                                exec(row["Command"])
                            except Exception, e:
                                rs.msg_sean("Scheduled problem: {} error: {}".format(row["Command"],str(e)), token)
            old_minute = minute
            try:
                event_json = json.loads(open_connection.recv())
            except:
                rs.msg_sean(str(open_connection.recv()), token)

            event = SlackEvent(event_json, cur, token)
            if 'user' in event_json.keys():
                event_json['user'] = event.name
            if 'channel' in event_json.keys():
                event_json['channel'] = event.channel_name

            if icolor >= len(colors):
                icolor = 0
            if ('message' not in event.etype) and event.subtype != "bot_message":
                print rs.colorize(event_json, icolor)
                icolor = icolor + 1
            else:

                if event.etype == 'message':
                    if 'gif me ' in event.text:
                        sql = "SELECT * FROM Gif_Whitelist WHERE Slack_Id = %s AND Channel = %s"
                        query = cur.execute(sql, (event.user_id, event.channel_id))
                        if query > 0 or (event.channel_id == rs.get_im(event.user_id, token)):
                            user_authed = True
                        else:
                            user_authed = False

                        if (user_authed == True) or (event.user_id in super_users.values()):
                            tag = event.text.replace('gif me ', '').replace(' ', '+')
                            subprocess.Popen(["python", rs.get_shades_path() + "gifme.py", tag, event.channel_id], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                            print tag + ' ' + event.channel_id

                    if event.user_id in super_users.values():

                        if 'gif bless ' in event.text:
                            to_bless = event.text.replace('gif bless ', '')
                            sql = "SELECT * FROM Users WHERE Name LIKE %s OR Nick LIKE %s"
                            query = cur.execute(sql, (rs.like(to_bless), rs.like(to_bless)))
                            if query > 0:
                                row = cur.fetchone()
                                slackid = row["Slack_Id"]
                                to_bless = row["Name"]
                                sql = "SELECT * FROM Gif_Whitelist WHERE Slack_Id = %s AND Channel = %s"
                                query = cur.execute(sql, (slackid, event.channel_id))
                                if query > 0:
                                    message = "%s has already been blessed in this channel." % to_bless
                                else:
                                    sql = "INSERT INTO Gif_Whitelist (Slack_Id, Channel) VALUES(%s, %s)"
                                    cur.execute(sql, (slackid, event.channel_id))
                                    message = to_bless + " has been blessed with gif me powers in this channel."
                            else:
                                message = "Sorry brochinski, I don't know who " + to_bless + " is."
                            rs.post(event.channel_id, message, "based GIF GODS", token, icon_emoji=":fire:")

                        if 'gif revoke ' in event.text:
                            to_revoke = event.text.replace('gif revoke ', '')
                            sql = "SELECT * FROM Users WHERE Name LIKE %s or Nick LIKE %s"
                            query = cur.execute(sql, (rs.like(to_revoke), rs.like(to_revoke)))
                            if query > 0:
                                row = cur.fetchone()
                                slackid = row["Slack_Id"]
                                to_revoke = row["Name"]
                                sql = "SELECT * FROM Gif_Whitelist WHERE Slack_Id = %s AND Channel = %s"
                                query = cur.execute(sql, (slackid, event.channel_id))
                                if query > 0:
                                    sql = "DELETE FROM Gif_Whitelist WHERE Slack_Id = %s AND Channel = %s"
                                    cur.execute(sql, (slackid, event.channel_id))
                                    message = to_revoke + ' has been damned by the gif gods.'
                                else:
                                    message = to_revoke + " ain't blessed, yo"
                            else:
                                message = "Sorry brochinski, I don't know who " + to_revoke + " is."
                            rs.post(event.channel_id, message, "based GIF GODS", token, icon_emoji=":fire:")

                        if "!shutdown" in event.text:
                            rs.post(event.channel_id, 'going down', 'shades', token)
                            kill_me = True

                        if "!restart" in event.text:
                            rs.post(event.channel_id, 'restarting and updating, be back shortly', 'shades', token)
                            subprocess.Popen(["bash", rs.get_shades_path() + "restart.sh"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                            kill_me = True

                        if "shades channel_police " in event.text:
                            if 'off' in event.text:
                                dats_the_sound_of_da_police == False
                                rs.msg_sean('Channel police has been turned off', token)
                            if 'on' in event.text:
                                dats_the_sound_of_da_police == True
                                rs.msg_sean('Channel police is back on baby!', token)

                        if "dbdump " in event.text:
                            try:
                                db = event.text.replace("dbdump ", "")
                                # getting extra quotes if we cur.execut(sql, (db)) on this one
                                sql = "SELECT * FROM {}".format(db)
                                query = cur.execute(sql)
                                if query > 0:
                                    temp_arr = []
                                    rows = cur.fetchall()
                                    for row in rows:
                                        temp_arr.append(row)
                                    data = str(temp_arr)
                                    message = data
                                else:
                                    message = "yo, I don't have {} in my db".format(db)
                            except Exception, e:
                                message = "problem with {}: \r {}".format(db, e)
                            rs.msg_sean(message, token)

                        if "shades tweet: " in event.text:
                            tweet = event.text.replace("shades tweet: ", "")
                            tweet = "{}".format(tweet)
                            subprocess.Popen(["python", rs.get_shades_path() + "tweet.py", tweet], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                            message = "Sending tweet :bird:"
                            rs.post(event.channel_id, message, "tweetyshadesofgrey", token, icon_emoji=":bird:")

                        if "!schedule " in event.text:
                            try:
                                commands = event.text.replace("!schedule ", "")
                                weekday = re.search(r'(?<=w\:)\S+', commands).group()
                                hour = re.search(r'(?<=h\:)\d+', commands).group()
                                minute = re.search(r'(?<=m\:)\d+', commands).group()
                                command = re.search(r'(?<=cmd\:).*', commands).group()

                                sql = "INSERT INTO Tasks (Command, Weekday, Hour, Min) VALUES(%s, %s, %s, %s)"
                                cur.execute(sql, (command, weekday, hour, minute))
                                message = "Successfully scheduled task"
                            except Exception, problem:
                                message = "Couldn't schedule because: {}".format(problem)
                            rs.post(event.channel_id, message, "shades mcstatus", token)

                        if "reload resources" in event.text:
                            try:
                                reload(rs)
                                message = "Successfully reimported our resources file"
                            except:
                                message = "Was unable to reimport resources.py"
                            rs.msg_sean(message, token)

                        if re.search(r'^!e', event.text) != None:
                            code = event.text.replace("DOT", ".")
                            if re.search(r'^!ev ', event.text) != None:
                                code = code.replace("!ev ", "")
                                try:
                                    message = str(eval(code))
                                    rs.post(event.channel_id, message, 'shades mcPythonInterpreter', token)
                                except Exception, e:
                                    message = str(e)
                                    rs.post(event.channel_id, message, 'shades mcPythonInterpreter', token)

                            if re.search(r'^!ex ', event.text) != None:
                                code = code.replace("!ex ", "")
                                print code
                                try:
                                    exec(code)
                                    message = "success"
                                except Exception, e:
                                    message = str(e)
                                rs.post(event.channel_id, message, 'shades mcPythonInterpreter', token)
Ejemplo n.º 2
0
                                                    message = message + "{}: {}\r\n".format(name, row['Moniker'])
                                if command == "reset":
                                    network = msg_items[-1]
                                    if network == 'all':
                                        sql = "DELETE FROM Monikers WHERE Slack_Id = '{}'".format(event.user_id)
                                        cur.execute(sql)
                                        message = "All monikers belonging to you have been deleted."
                                    else:
                                        sql = "DELETE FROM Monikers WHERE Slack_Id = '{}' AND Network = '{}'".format(event.user_id, network)
                                        cur.execute(sql)
                                        message = "All monikers on {} belonging to you have been removed.".format(network)
                                #if command == "search":
                                 #   search_for = msg_items[-1]
                                  #  if search_for == 'search':
                                   #     message = "Please specify something to search for. `!monikers search name/network`"
                        user_dm = rs.get_im(event.user_id, token)
                        rs.post(user_dm, message, 'shades McMoniker', token, icon_emoji=':robot:')
                        if event.channel_id != user_dm:
                            rs.post(event.channel_id, "just dm'd you bruv", 'shades McMoniker', token, icon_emoji=':robot:')

                    if re.search(r'^!shades help$', event.text) != None:
                        message = """ Here's a list of things I can do:
                         `!2n` - lets you check the 2n status of any team
                            `!2n status assessments` this will return x/y where x is current open JIRAs and y is the team's 2n number
                            `!2n change newteam 3` this will change newteam's n number to 3, or add newteam to the bot with an n number of 3.
                            `!2n add newteam 3` same as above
                            `!2n delete newteam` will delete the team 'newteam' from the bot. admin only
                            `!2n add_nick nickname team` will add a nickname for a team, then `!2n status nickname` will fetch data for team
                                (can use one nick name for multiple teams, ex. mobile will call both ios and android)
                            `!2n delete_nick nickname` will remove all nicknames matching nickname from the database.
                            `!2n query team` will show you the current JIRA query that team is following.