def __main__(): token = os.getenv('stoken') tag = str(sys.argv[1]) channel = str(sys.argv[2]) requrl = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" + tag try: gifjson = requests.get(requrl, timeout=5).json() gifurl = gifjson[u"data"][u"image_url"] except: gifurl = 'Sorry bruv, no gifs found with tag(s): ' + tag rs.post(channel, gifurl, 'shades McGee (gif extraordinaire)', token, icon_emoji=":gif:")
def main(): """main function""" db_msg = "" token = os.getenv('stoken') team = str(sys.argv[1]) n_number = 2*int(sys.argv[2]) channel = str(sys.argv[3]) stat = str(sys.argv[4]) con = mdb.connect('localhost', os.getenv('dbuser1'), os.getenv('dbpass1'), 'rtm', cursorclass=MySQLdb.cursors.DictCursor) cur = con.cursor() sql = "SELECT * FROM 2n_Teams WHERE Team = %s" cur.execute(sql, (team)) row = cur.fetchone() query = row["Query"] jiracred = (os.getenv('juser') + ':' + os.getenv('jpass')).encode('base64', 'strict') headers = {'Authorization': 'Basic ' + jiracred} if query == None: base = "https://{}.atlassian.net/rest/api/2/search?jql=".format(os.getenv('jiradomain')) jql = (base + '(status%20%20%3D%20Open%20OR%20status%20%3D%20"In%20Progress"' '%20OR%20status%20%3D%20"QA"%20OR%20status%20%3D%20Feedback%20or' '%20status%20%3D%20"QA%20Ready")%20AND%20type%20%3D%20Bug%20AND' '%20("Sprint%20Team"%20%3D%20%27' + team + '%27)') else: jql = query response = requests.get(jql, headers=headers) try: ticket_count = float(response.json()[u'total']) n_diff = ticket_count - n_number n_percentage = round((n_diff/n_number) * 100, 2) n_ratio = round(ticket_count/(n_number/2), 2) if stat == "True": now = time.time() sql = ("INSERT INTO 2n_data (Team, N_number, Count, Date) " "VALUES('{}', '{}', '{}', '{}')").format(team, n_number, ticket_count, now) cur.execute(sql) con.commit() db_msg = "\r\nSuccessfully added this team and their 2n number to the db for today." if n_diff > 0: message = ("{} has {}/{} tickets that count towards 2n. " "That's {}% over 2n with an N ratio of {}n.") message = message.format(team, int(ticket_count), n_number, n_percentage, n_ratio) else: message = "{} has {}/{} tickets that count towards 2n." message = message.format(team, int(ticket_count), str(n_number)) rs.post(channel, message + db_msg, 'shades McGee', token, icon_emoji=':shadesmcgee:') except KeyError: message = ("Looks like JIRA doesn't have {} as a sprint team, " "please add your team to the sprint team field.") message = message.format(team) rs.post(channel, message, 'shades McGee', token, icon_emoji=':shadesmcgee:') except Exception, e: message = "Oops, something went wrong. If this persists, please contact @slewis. \n" + e rs.post(channel, message, 'shades McGee', token, icon_emoji=':shadesmcgee:')
def main(): """main function""" db_msg = "" token = os.getenv('stoken') team = str(sys.argv[1]) n_number = 2 * int(sys.argv[2]) channel = str(sys.argv[3]) stat = str(sys.argv[4]) con = mdb.connect('localhost', os.getenv('dbuser1'), os.getenv('dbpass1'), 'rtm', cursorclass=MySQLdb.cursors.DictCursor) cur = con.cursor() sql = "SELECT * FROM 2n_Teams WHERE Team = %s" cur.execute(sql, (team)) row = cur.fetchone() query = row["Query"] jiracred = (os.getenv('juser') + ':' + os.getenv('jpass')).encode( 'base64', 'strict') headers = {'Authorization': 'Basic ' + jiracred} if query == None: base = "https://{}.atlassian.net/rest/api/2/search?jql=".format( os.getenv('jiradomain')) jql = ( base + '(status%20%20%3D%20Open%20OR%20status%20%3D%20"In%20Progress"' '%20OR%20status%20%3D%20"QA"%20OR%20status%20%3D%20Feedback%20or' '%20status%20%3D%20"QA%20Ready")%20AND%20type%20%3D%20Bug%20AND' '%20("Sprint%20Team"%20%3D%20%27' + team + '%27)') else: jql = query response = requests.get(jql, headers=headers) try: ticket_count = float(response.json()[u'total']) n_diff = ticket_count - n_number n_percentage = round((n_diff / n_number) * 100, 2) n_ratio = round(ticket_count / (n_number / 2), 2) if stat == "True": now = time.time() sql = ("INSERT INTO 2n_data (Team, N_number, Count, Date) " "VALUES('{}', '{}', '{}', '{}')").format( team, n_number, ticket_count, now) cur.execute(sql) con.commit() db_msg = "\r\nSuccessfully added this team and their 2n number to the db for today." if n_diff > 0: message = ("{} has {}/{} tickets that count towards 2n. " "That's {}% over 2n with an N ratio of {}n.") message = message.format(team, int(ticket_count), n_number, n_percentage, n_ratio) else: message = "{} has {}/{} tickets that count towards 2n." message = message.format(team, int(ticket_count), str(n_number)) rs.post(channel, message + db_msg, 'shades McGee', token, icon_emoji=':shadesmcgee:') except KeyError: message = ("Looks like JIRA doesn't have {} as a sprint team, " "please add your team to the sprint team field.") message = message.format(team) rs.post(channel, message, 'shades McGee', token, icon_emoji=':shadesmcgee:') except Exception, e: message = "Oops, something went wrong. If this persists, please contact @slewis. \n" + e rs.post(channel, message, 'shades McGee', token, icon_emoji=':shadesmcgee:')
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)
if re.search(r'^!2n status \S*$', event.text) != None: team = event.text.replace('!2n status ', '') rs.two_n(team, event.channel_id, token, cur) if re.search(r'^!2n help$', event.text) != None: help_msg = """`!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. `!2n change_query team new_query` will set new_query to be used when team is called by !2n status, new_query must be a valid JIRA api/ui search URL""" rs.post(event.channel_id, help_msg, '2n bot', token, icon_emoji=':robot:') if re.search(r'^!2n change \S* \d*$', event.text) or re.search(r'^!2n add \S* \d*$', event.text): msg_items = re.search(r'^!2n \w* \S* \d*$', event.text).group().split(' ') team = msg_items[2] n_number = int(msg_items[3]) sql = "SELECT * FROM 2n_Teams WHERE Team = %s" query = cur.execute(sql, (team)) if query > 0: team_row = cur.fetchone() current_n = int(team_row["N_Number"]) if current_n != n_number: sql = "UPDATE 2n_Teams SET N_Number = %s WHERE Team = %s" cur.execute(sql, (n_number, team)) message = team + ' n number changed from ' + str(team_row["N_Number"]) + ' to ' + str(n_number) else:
def __main__(): slack_token = str(sys.argv[1]) channel = str(sys.argv[2]) con = mdb.connect('localhost', os.getenv('dbuser1'), os.getenv('dbpass1'), 'rtm', cursorclass=MySQLdb.cursors.DictCursor) cur = con.cursor() cur.execute("SELECT * FROM Monikers WHERE Network = ':league:'") full_list = cur.fetchall() leaguers = list(chunks(full_list, 35)) bad_names = [] for leaguer_list in leaguers: namelist = [] for leaguer in leaguer_list: name = leaguer["Moniker"] namelist.append(name) namelist = ','.join(namelist) for summoner in summoner_get_by_name(namelist).items(): summoner = summoner[1] sql = "SELECT * FROM League WHERE S_ID = '%s'" query = cur.execute(sql, (summoner["id"])) if query == 0: # add the user to the League table if they're not in it yet sql = "SELECT * FROM Monikers WHERE Network = ':league:' AND Moniker = %s" query = cur.execute(sql, (summoner["name"])) if query > 0: user = cur.fetchone() sql = "INSERT INTO League (Slack_Id, Name, S_ID, Level) VALUES(%s, %s, %s, %s)" cur.execute(sql, (user["Slack_Id"], summoner["name"], summoner["id"], summoner["summonerLevel"])) else: bad_names.append(summoner["name"]) else: # update the user in the table if their level changes rank = summoner_get_current_rank(summoner["id"]) rank_sql = "SELECT * FROM League WHERE S_ID = %s AND Rank = %s" rank_query = cur.execute(rank_sql, (summoner["id"], rank)) sql = "SELECT * FROM League WHERE S_ID = '%s' AND Level = '%s'" query1 = cur.execute(sql, (summoner["id"], summoner["summonerLevel"])) # now check to make sure they're in the Moniker table # (riot api fuzzy matches names better than i can) sql = "SELECT * FROM Monikers WHERE Network = ':league:' AND Moniker = %s" query = cur.execute(sql, (summoner["name"])) if query > 0 and query1 == 0: user = cur.fetchone() sql = "UPDATE League SET Level = %s WHERE S_ID = %s" cur.execute(sql, (summoner["summonerLevel"], summoner["id"])) sql = "SELECT * FROM Users WHERE Slack_Id = %s" cur.execute(sql, (user["Slack_Id"])) frd_user = cur.fetchone() message = "omg {}/{} just leveled up to {}".format(frd_user["Nick"], summoner["name"], summoner["summonerLevel"]) rs.post(channel, message, "LoL shades", slack_token, icon_emoji=':league:') if query > 0 and rank_query == 0: user = cur.fetchone() sql = "UPDATE League SET Rank = %s where S_ID = %s" cur.execute(sql, (rank, summoner["id"])) if rank != "Currently Unranked": sql = "SELECT * FROM Users WHERE Slack_Id = %s" cur.execute(sql, (user["Slack_Id"])) frd_user = cur.fetchone() message = "omg {}/{} just changed ranks to {}.".format(frd_user["Nick"], summoner["name"], rank) rs.post(channel, message, "LoL shades", slack_token, icon_emoji=':league:') time.sleep(1) con.commit() if len(bad_names) > 0: rs.msg_sean("bad names in monikers for :league: :" + ", ".join(bad_names), slack_token)