def scrape_match(tba_key: str, year : int, event_name : str, match_num : int, match_type='qm', round=False): '''Given TBA-Authentication key, Competition year, event name, and match number, queries TBA for basic match data of each team in the match.''' tba = tbapy.TBA(tba_key) year = int(year) match_num = int(match_num) round = int(round) event_key = '' red_data = [] blue_data = [] for event in tba.events(year): if event.name == event_name: event_key = event.key break red_alliance_teams = tba.match(year=year, event=event_key, type=match_type, number=match_num)['alliances']['red']['team_keys'] if match_type=='qm' else tba.match(year=year, event=event_key, type=match_type, number=match_num, round=round)['alliances']['red']['team_keys'] blue_alliance_teams = tba.match(year=year, event=event_key, type=match_type, number=match_num)['alliances']['blue']['team_keys'] if match_type=='qm' else tba.match(year=year, event=event_key, type=match_type, number=match_num, round=round)['alliances']['blue']['team_keys'] for team in red_alliance_teams: team_data = tba.team_status(team, event_key)['qual']['ranking']['sort_orders'] red_data.append(team_data) for team in blue_alliance_teams: team_data = tba.team_status(team, event_key)['qual']['ranking']['sort_orders'] blue_data.append(team_data) return red_data, blue_data
def load_match_list(request): #use arkansas for testing but change to heartland later event = "2018iacf" tba = tbapy.TBA("jwEmVymeOvhRakjCQWJS4sE4GHxD4TBKhXVsgtTtqLPvODraEbRtYz3YlmhddAkD") matchObjects = tba.event_matches(event, simple=True) master_schedule = [] for match_ew in matchObjects: # Create the match list match = creatematchdata(match_ew) matchlevel = getattr(match_ew, "comp_level") if 'qm' not in matchlevel: print matchlevel else: new_match = Match(match_number=match[0], blue_one=match[1], blue_two=match[2], blue_three=match[3], red_one=match[4], red_two=match[5], red_three=match[6]) new_match.save() # Write out the data to a dictionary to be used master_schedule.append(match) return render(request, "scoutapp2018/load_match_list.html")
def get_team_list(event: str, tba_key: str) -> list: tba = tbapy.TBA(keys.key) teams = tba.event_teams(event) team_list = [] for team in teams: str_team = team.get('key') team_num = int(str_team[3:]) team_list.append(team_num) return sorted(team_list)
def update_tba(): tba = tbapy.TBA(os.getenv("TBA_KEY")) year = tba.status().current_season teams = {} team_objects = {} i = 0 while True: api_teams = tba.teams(i, year) i += 1 if len(api_teams) == 0: print("Finished with teams") break for team in api_teams: print("Team %d: %s" % (team.team_number, team.nickname)) q = FRCTeam.objects.filter(key=team.key) if len(q) > 0: t = q.first() else: t = FRCTeam() t.key = team.key t.number = team.team_number t.nickname = team.nickname t.save() teams[team.key] = team team_objects[team.key] = t for event in tba.events(year): print(event.name) q = FRCComp.objects.filter(compCode=event.key) if len(q) > 0: e = q.first() else: e = FRCComp() e.compCode = event.key e.shortName = event.short_name e.longName = event.name e.save() for team in tba.event_teams(event.key, simple=True): try: t = FRCTeam.objects.filter(key=team.key).first() e.teams.add(t) e.save() except: print("Error adding %s to %s" % (team.nickname, e.short_name))
def fetch(team, event, token): """ Fetch and store TBA data for use on dashboard. :param team: Team to tailor data to. :param event: Key of event to get data on. :param token: TBA token to use for fetching data. """ # Initialize TBA API tba = tbapy.TBA(token) print('Getting Team #{team}\'s matches at event {event}...'.format(team=team, event=event)) # Fetch matches that the team is in at this competition matches = tba.team_matches(team, event) # Sort matches matches = sorted(matches, key=lambda match: (['qm', 'qf', 'sf', 'f'].index(match.comp_level), match.match_number)) print('Getting stats for event {event}...'.format(event=event)) # Fetch the event's stats stats = {'oprs': tba.event_oprs(event).oprs} insights = {'insights': tba.event_insights(event)} print('{num_matches} matches fetched and processed. Building team list... (may take a while)'.format(num_matches=len(matches))) # Make a new array to hold all the teams that played in those matches teams = [match.alliances['red']['team_keys'] + match.alliances['blue']['team_keys'] for match in matches] # Flatten list and remove duplicates teams = list(set([tm for alliance in teams for tm in alliance])) # Create a new hash to store data about the teams team_data = {} # Fetch the data for each team for tm in teams: # Create a new element containing the data of this team # (Turn string form [i.e. 'frc1418'] into integer, i.e. 1418) team_data[tm] = tba.team(tm) print('Data fetched for team {team}.'.format(team=tm[3:])) print('Storing data...') # Write team and match data into their respective files. with open('static/data/teams.json', 'w+') as f: json.dump(team_data, f) with open('static/data/matches.json', 'w+') as f: json.dump(matches, f) with open('static/data/stats.json', 'w+') as f: json.dump(stats, f) with open('static/data/insights.json', 'w+') as f: json.dump(insights, f) print('{num_matches} matches and {num_teams} teams fetched.'.format(num_matches=len(matches), num_teams=len(teams))) print('Data saved in directory static/data/.')
def __init__(self, bot): self.bot = bot # If we are in Heroku then TBAKEY will be defined tba_key = os.getenv('TBAKEY') if tba_key: self.tba = tbapy.TBA(tba_key) else: # If we are in development then open the key from file with open('../tba_key.txt', 'r') as file: tba_key = file.readline() self.tba = tbapy.TBA(tba_key) self.teams_table = PrettyTable() self.teams_table.field_names = ['Team Name'] # Max length of discord message self.MAX_LENGTH = 1900
def get_tba_teams(use_all_events=False, district=DISTRICT_KEY, year=YEAR): tba = tbapy.TBA( 'LhxxYeNje0x2oOcMs4d2DTp45We5fTLHek2MNaDzd0v5WqrvbwBtDJaa8I47YfqA') if use_all_events: teams = [] for i in range(50): teams = teams + tba.teams(i, simple=True) else: teams = tba.district_teams(district, simple=True) team_nums = [t['key'] for t in teams] return team_nums
def setup(apiKey="TBA_KEY", useEnv=True): ''' Sets up tbapy with an API key from a system environment variable :param str apiKey: The TBA API key or system environment variable name for it :param bool useEnv: Set to True to fetch TBA API key from environment variable :return: Instance of TBA ''' if useEnv: apiKey = os.getenv(apiKey) return tbapy.TBA(apiKey)
def calculate_defense(team_number): tba = tbapy.TBA(sensitiveInfo.tba_api_key()) event = "2019dar" timds = get_timds(team_number) for timd in timds: alliance = timd['header']['driversStation'][:3] opposing_teams = [ get_team(int(team[3:])) for team in tba.match(year=2019, event=event, type='qm', number=int(timd['match_number'])) ['alliances'][alliance]['team_keys'] ] opposing_timds = [ timd_ for timd_ in [team['timds'] for team in opposing_teams] if int(timd_['match_number']) == int(timd['match_number']) ] drops_caused = len([ cycles.filter_timeline_actions([opposing_timds], actionType='drop', wasDefended=True) ]) hatch_cycle_time_decreased = stats.avg([ stats.percent_difference( timd_['calculated']['undefendedHatchAverageCycleTime'], timd_['calculated']['defendedHatchAverageCycleTime']) for timd_ in opposing_timds if timd_['calculated']['defendedHatchAverageCycleTime'] != 0 and timd_['calculated']['defendedHatchAverageCycleTime'] != 0 ]) cargo_cycle_time_decreased = stats.avg([ stats.percent_difference( timd_['calculated']['undefendedCargoAverageCycleTime'], timd_['calculated']['defendedCargoAverageCycleTime']) for timd_ in opposing_timds if timd_['calculated']['defendedCargoAverageCycleTime'] != 0 and timd_['calculated']['defendedCargoAverageCycleTime'] != 0 ]) cycle_percent_reduction = stats.avg([ stats.percent_difference( timd_['calculated']['totalTeleopCycles'], get_team(int( timd_['teamNumber']))['totals']['avgTotalTeleopCycles']) for timd_ in opposing_timds if timd_['calculated']['timeDefending'] < 80 ])
def get_match_results(event_key, match_key): tba = tbapy.TBA( "wvIxtt5Qvbr2qJtqW7ZsZ4vNppolYy0zMNQduH8LdYA7v2o1myt8ZbEOHAwzRuqf") match_data = tba.match("_".join([event_key, match_key])) if match_data is None: raise ValueError( """{} {} does not exist on TBA. Please use a match that exists""". format(event_key, match_key)) blue_data, red_data = parse_data(match_data) while (blue_data[0] == -1 or red_data[0] == -1): print "Waiting 1 minute for TBA to update scores" time.sleep(60) match_data = event_get(event_key).get_match(match_key) blue_data, red_data = parse_data(match_data) return blue_data, red_data
def main(): if len(sys.argv) == 1: print("Usage: get_awards.py [year|all]") return year = sys.argv[1] data = frontmatter.load("community.md")['teamlist'] tba = tbapy.TBA(os.environ['TBA_KEY']) if year == 'all': for year in data: update_year(tba, year, data) else: update_year(tba, year, data) print(yaml.dump(data, sort_keys=False))
def get_tba_access(): ''' Returns a TBA object, used to access TBA API If there is not a valid key in 'tba_key.json', it asks the user for a key and stores that. ''' filename = "tba_key.txt" try: file = open(filename, "r+") except: open(filename, "w") file = open(filename, "r+") key = file.read() if (key == ""): key = input("Enter a valid TBA authentication key\n") file.write(key) tba = tbapy.TBA(key) file.close() return tba
def __init__(self, key, years): """Initialise Cassandra Args: key: String of TBA key. years: List of the years in which to cache results. """ self.years = years self.key = key # cache previous results events = {} matches = {} tba = tbapy.TBA(self.key) # fetch events by year and order chronologically for year in years: r = tba.events(year, simple=True) # sort by date and don't include offseason events a = sorted(r, key=lambda b: b["start_date"]) a = [i["key"] for i in a if i["event_type"] < 99] events[str(year)] = a # fetch matches by year and event for year in years: for event in events[str(year)]: r = tba.event_matches(event) matches[event] = r # save to cache store = DataStore(new_data_store=False, year_events=events) for year in years: for event in events[str(year)]: event_matches = matches[event] store.add_event_matches(str(year), event, event_matches) self.matches = matches
def __init__(self, years): """Create the Store class for the specified years. Args: years (list): Of years to use for Store. """ def _new_tba_get(self, url): resp = self.session.get(self.URL_PRE + url, headers={'X-TBA-Auth-Key': self.auth_key, 'If-Modified-Since': self.last_modified}) if resp.status_code == 200: self.last_modified_response = resp.headers['Last-Modified'] return resp.json() else: return {} tbapy.TBA._get = _new_tba_get key = open("key.txt").read().strip("\n") self.years = years self.matches = {} self.events = {} if not os.path.exists("cache/"): os.mkdir("cache") self.tbapy = tbapy.TBA(key) new = self.tbapy.events(2008) print(self.tbapy.last_modified) print(self.tbapy.last_modified_response) for year in self.years: # cache year if does not exist if not os.path.exists("cache/" + str(year) + self.FILE_EXTENSION): self.cache_matches(year) # check for update of year if it does exist else: self.check_for_update(year)
def get_tba_data(weeks=range(10), start_time=0, end_time=time.time(), use_all_events=False, district=DISTRICT_KEY, year=YEAR): tba = tbapy.TBA( 'LhxxYeNje0x2oOcMs4d2DTp45We5fTLHek2MNaDzd0v5WqrvbwBtDJaa8I47YfqA') print("Loading event data...") #get events #events = tba.team_events(TEAM_NUM ,YEAR ,simple=True) if use_all_events: events = tba.events(year=year) else: events = tba.district_events(district) event_ids = [] for e in events: if e['week'] in weeks or (e['week'] == None and 0 in weeks): event_ids.append(e['key']) print("Loading match data...") matches = [] for event_c in event_ids: event_matches = tba.event_matches(event_c) week = tba.event(event_c)['week'] event_data = [] for mat in event_matches: actual_time = mat['actual_time'] if actual_time > start_time and actual_time < end_time: event_data.append({'blue':mat['alliances']['blue']['team_keys'], 'red':mat['alliances']['red']['team_keys'],\ 'scores':(mat['alliances']['blue']['score'],mat['alliances']['red']['score']),\ 'week':week}) matches += event_data #get teams print('Loading team data...') team_nums = get_tba_teams(use_all_events, district) return team_nums, matches
import tbapy from slackbot.bot import respond_to tba = tbapy.TBA('NRIotr26Z49TOHAI1H1VQtrZ9rXQOaApuia9oCr9pbwsWImjbDNYU4f3znFdlvea') @respond_to("detail (\d+)") def detail(message, number): team = tba.team(int(number)) reply = "Team %s, %s, out of %s, %s %s. %s - Founded in %s." % (int(number), team.nickname, team.city, team.state_prov, team.country, team.website, team.rookie_year) message.reply(reply)
import wx import tbapy tba = tbapy.TBA( "ydQbaifEuIbNjHS2cKFNXGfVDGrMsjwSOyqws9InphNYaQfyh6D11NHnyEuPWglc") class testFrame(wx.Frame): def __init__(self, *args, **kw): super(testFrame, self).__init__(*args, **kw) self.events = tba.team_events(5829, "2018", True, False) panel_one = wx.Panel(self) title = wx.StaticText(panel_one, label="Test App Title", pos=(600, 15)) font_one = title.GetFont() font_one.PointSize += 10 font_one = font_one.Bold() title.SetFont(font_one) self.makeMenuBar() self.CreateStatusBar() self.SetStatusText("Welcome to Scouting App V1") def makeMenuBar(self): fileMenu = wx.Menu() team_city_item = fileMenu.Append( -1, "Team City...\tCtrl-T", "Help string shown in menu for this item") team_events_item = fileMenu.Append(0, "Team events...\tCtrl-E", "Help") alliance_info_item = fileMenu.Append(1, "Alliance Info...\tCtrl-A", "Help")
from tqdm import tqdm import awardTypes import tbapy import json import os tba = tbapy.TBA(os.getenv('TBA_KEY')) def get_year_data(): teams_data = {} for year in tqdm(range(1992, 2020)): s_year = str(year) s1_year = str(year - 1) teams_data[s_year] = {'teams': tba.teams(year=year, keys=True), 'gains': [], 'losses': []} if s1_year in teams_data: teams_data[s_year]['gains'] = [team for team in teams_data[s_year]['teams'] if team not in teams_data[s1_year]['teams']] teams_data[s_year]['losses'] = [team for team in teams_data[s1_year]['teams'] if team not in teams_data[s_year]['teams']] else: teams_data[s_year]['gains'] = teams_data[s_year]['teams'] teams_data[s_year] = get_rookie_winners(year, teams_data[s_year]) with open('team_data_' + s_year + '.json', 'w') as fp: json.dump(teams_data[s_year], fp)
import sensitiveInfo homeDir = os.path.expanduser('~') # Firebase setup pyrebase_config = { "apiKey": sensitiveInfo.firebase_api_key(), "authDomain": "mri2019.firebaseapp.com", "databaseURL": "https://mri2019.firebaseio.com", "storageBucket": "mri2019.appspot.com", } firebase = pyrebase.initialize_app(pyrebase_config) database = firebase.database() # Setup for tbapy tba = tbapy.TBA(sensitiveInfo.tba_api_key()) event = "2019mnri" # Get a list of all qualifying matches at an event try: matches = [ match for match in tba.event_matches(event, simple=True) if match['comp_level'] == 'qm' ] print(matches[0]) # TODO Make this except clause more specfic except: print("Error getting matches from TBA, check event and API keys.") exit(1)
#!/usr/bin/python3 # -*- encoding: utf8 -*- ''' Created on Mar 28, 2017 @author: Jack Rausch ''' import json import tbapy import numpy as np import numpy.linalg as linalg #the key which alows this to work, currently un my(Waweru's) account might want to change AUTH_KEY = 'NJielZLWMugOBVVlzs9vgQaK9kgbDGZYLyLaAQPy1SrC1eOR3hkNS6MnIybonTCg' tba = tbapy.TBA(AUTH_KEY) simple = True def get_event_teams(event_key): jsonified = tba.event_teams(event_key, simple, simple) return jsonified """ Supplies the least sqaures solution to the probelm of assigning each team a stat when they are collected per alliance """ def getStat(reg_key, stat):
import tbapy import pandas as pd import json import numpy as np tba = tbapy.TBA( 'az3CfBMqtHsElcAwN9pdsjAlIVVHUTCcVPjYRBjPnCQOFqwZ6y9raUnmXXOhQiP7') # ######################GET WINS, LOSSES, TIES, and TOTAL RANKING POINTS################################# # all_teams = pd.read_csv('all_teams.csv') # events = pd.read_csv('2018events.csv') # events = events['event_code'].values # events = events # #events = map(eval, events) # statistics = pd.DataFrame() # for event in events: # print(event) # event_ranking = tba.event_rankings(event) # event_ranking = json.dumps(event_ranking, indent=4, sort_keys=True) # # print (event_ranking[1]) # # obj = json.loads(event_ranking) # keys = obj.keys() # # print(keys) # # print(obj['sort_order_info']) # # parkPoints = 1 # autoPoints = 2 # ownershipPoints = 3 # vaultPoints = 4 # # all_ranks = obj['rankings']
def __init__(self, auth_key, teams): self.tba = tbapy.TBA(auth_key) self.matches_announced = [] self.match_results_announced = [] self.refreshNewEvents() self.teams = teams
import mysql.connector as mariaDB import tbapy import string tba = tbapy.TBA( 'Tfr7kbOvWrw0kpnVp5OjeY780ANkzVMyQBZ23xiITUkFo9hWqzOuZVlL3Uy6mLrz') x = 195 team = tba.team(x) event = '2019cur' # This is the key for the event def sortbyteam(d): return d.get('team_number', None) conn = mariaDB.connect( user='******', passwd='Einstein195', host='frcteam195.cmdlvflptajw.us-east-1.rds.amazonaws.com', database='team195_scouting') cursor = conn.cursor() eventTeams = tba.event_teams(event) eventOpr = tba.event_oprs(event).get("oprs") eventoprSorted = [(k[3:], eventOpr[k]) for k in sorted(eventOpr, key=eventOpr.get, reverse=True)] print(eventoprSorted) for team in eventoprSorted: query = "INSERT INTO BlueAllianceOPR (Team, OPR) VALUES " + "('" + str(team[0]) + "', '" + \ str(team[1]) + "');" cursor.execute(query) conn.commit()
import tbapy import os hof_teams = [ 'frc16', 'frc23', 'frc27', 'frc51', 'frc67', 'frc103', 'frc111', 'frc120', 'frc175', 'frc236', 'frc254', 'frc341', 'frc359', 'frc365', 'frc597', 'frc842', 'frc987', 'frc1114', 'frc1538', 'frc2614', 'frc3132', 'frc2834', 'frc1311', 'frc1816', 'frc1902' ] tba = tbapy.TBA(os.getenv("TBA_KEY")) hof_matches = {} for team in hof_teams: print('on team', team) for year in tba.team_years(team): for match in tba.team_matches(team, year=year): red_bots = match['alliances']['red']['team_keys'] blue_bots = match['alliances']['blue']['team_keys'] alliance = red_bots if team in red_bots else blue_bots all_hof = True for bot in alliance: all_hof = all_hof and bot in hof_teams if all_hof: if match['key'] not in hof_matches: hof_matches[match['key']] = alliance print('\n\nHOF ALLIANCE MATCHES:') for key in hof_matches:
def findErrors(df): global apiKEY global eventCode print("Starting finding errors") tba = tbapy.TBA(apiKEY) finalMSG = "" try: matchNum = f"qm{mode(df['Match'])}" match_data = tba.match(f"{eventCode}_{matchNum}") except: return "NI" blueScore = match_data["alliances"]["blue"]["score"] redScore = match_data["alliances"]["red"]["score"] print(blueScore) print(redScore) scoreBreakdown = match_data["score_breakdown"] # Set counters redInnerAuto = 0 redOuterAuto = 0 redLowerAuto = 0 blueInnerAuto = 0 blueOuterAuto = 0 blueLowerAuto = 0 redInnerTele = 0 redOuterTele = 0 redLowerTele = 0 blueInnerTele = 0 blueOuterTele = 0 blueLowerTele = 0 for index, row in df.iterrows(): # Get alliance station alliance = row['Alliance'][:1] drive_station = row['Alliance'][1:] # Get correct alliance data if alliance == "R": allianceBreakdown = scoreBreakdown['red'] # AUTO SCORING redInnerAuto += row["A_Inner"] redOuterAuto += row['A_Outer'] redLowerAuto += row["A_Lower"] # TELE SCORING redInnerTele += row["T_Inner"] redOuterTele += row['T_Outer'] redLowerTele += row["T_Lower"] else: allianceBreakdown = scoreBreakdown['blue'] # AUTO SCORING blueInnerAuto += row["A_Inner"] blueOuterAuto += row['A_Outer'] blueLowerAuto += row["A_Lower"] # TELE SCORING blueInnerTele += row["T_Inner"] blueOuterTele += row['T_Outer'] blueLowerTele += row["T_Lower"] # Gets known values on a per robot basis measuredMovement = allianceBreakdown[f'initLineRobot{drive_station}'] # INITIATION LINE CHECK # Convert string to boolean if measuredMovement == "Exited": measuredMovement = 1 else: measuredMovement = 0 # Check if value of initiation line is correct. if row['Movement'] != measuredMovement: finalMSG += f"\n{row['Team']} incorrect initiation line value." # HANGING/PARK CHECK # Convert park data if row['Park'] == "Success": parkStatus = 1 else: parkStatus = 0 # Convert hang data if row['Hang'] == "Success" or row['cargo'] == 1: climbStatus = 1 else: climbStatus = 0 # Check if you are climbing and parking at the same time if climbStatus == 1 and parkStatus == 1: finalMSG += f"\n{row['Team']} is both parking and climbing at the same time." # Verify climbs are correct measuredEndgame = allianceBreakdown[f'endgameRobot{drive_station}'] # Convert data if measuredEndgame == "Hang": measuredClimbStatus = 1 measuredParkStatus = 0 elif measuredEndgame == "Park": measuredClimbStatus = 0 measuredParkStatus = 1 else: measuredParkStatus = 0 measuredClimbStatus = 0 # Checking our data! if climbStatus != measuredClimbStatus: finalMSG += f"\n{row['Team']} climbing data is invalid, please review." if parkStatus != measuredParkStatus: finalMSG += f"\n{row['Team']} parking status is incorrect." # Check scout names if "null" in row['Scout']: finalMSG += f"\n{row['Alliance']} has no scout name set." # Check AUTO SCORES # Inner scores if redInnerAuto != scoreBreakdown['red']['autoCellsInner']: finalMSG += f"\nRED alliance inner auto is off by {(redInnerAuto - scoreBreakdown['red']['autoCellsInner'])}" if blueInnerAuto != scoreBreakdown['blue']['autoCellsInner']: finalMSG += f"\nBLUE alliance inner auto is off by {(blueInnerAuto - scoreBreakdown['blue']['autoCellsInner'])}" # Outer scores if redOuterAuto != scoreBreakdown['red']['autoCellsOuter']: finalMSG += f"\nRED alliance outer auto is off by {(redOuterAuto - scoreBreakdown['red']['autoCellsOuter'])}" if blueOuterAuto != scoreBreakdown['blue']['autoCellsOuter']: finalMSG += f"\nBLUE alliance outer auto is off by {(blueOuterAuto - scoreBreakdown['blue']['autoCellsOuter'])}" # Lower scores if redLowerAuto != scoreBreakdown['red']['autoCellsBottom']: finalMSG += f"\nRED alliance lower auto is off by {(redLowerAuto - scoreBreakdown['red']['autoCellsBottom'])}" if blueLowerAuto != scoreBreakdown['blue']['autoCellsBottom']: finalMSG += f"\nBLUE alliance lower auto is off by {(blueLowerAuto - scoreBreakdown['blue']['autoCellsBottom'])}" # Check TELE SCORES # Inner scores if redInnerTele != scoreBreakdown['red']['teleopCellsInner']: finalMSG += f"\nRED alliance inner teleop is off by {(redInnerTele - scoreBreakdown['red']['teleopCellsInner'])}" if blueInnerTele != scoreBreakdown['blue']['teleopCellsInner']: finalMSG += f"\nBLUE alliance inner teleop is off by {(blueInnerTele - scoreBreakdown['blue']['teleopCellsInner'])}" # Outer scores if redOuterTele != scoreBreakdown['red']['teleopCellsOuter']: finalMSG += f"\nRED alliance outer teleop is off by {(redOuterTele - scoreBreakdown['red']['teleopCellsOuter'])}" if blueOuterTele != scoreBreakdown['blue']['teleopCellsOuter']: finalMSG += f"\nBLUE alliance outer teleop is off by {(blueOuterTele - scoreBreakdown['blue']['teleopCellsOuter'])}" # Lower scores if redLowerTele != scoreBreakdown['red']['teleopCellsBottom']: finalMSG += f"\nRED alliance lower teleop is off by {(redLowerTele - scoreBreakdown['red']['teleopCellsBottom'])}" if blueLowerTele != scoreBreakdown['blue']['teleopCellsBottom']: finalMSG += f"\nBLUE alliance lower teleop is off by {(blueLowerTele - scoreBreakdown['blue']['teleopCellsBottom'])}" if finalMSG == "": finalMSG = "no changes needed, please close the window" return finalMSG # while True: # with open("dovalidate.txt", "r") as f: # save = f.read() # if save.count("g")>0: # # move to somewhere better # with open("dovalidate.txt", "w+") as f: # f.write("stop") # if(is_connected("www.thebluealliance.com")): # tba = tbapy.TBA(apiKEY) # tba.match("2019onsh_qm19") # # # else: # time.sleep(10)
import tbapy from pathlib import Path TBAkey = "yZEr4WuQd0HVlm077zUI5OWPfYsVfyMkLtldwcMYL6SkkQag29zhsrWsoOZcpbSj" database = input("Database name: ") #Check database exists tempPath = Path(database) if not tempPath.is_file(): print("That database does not exist") exit(1) conn = sql.connect(database) cur = conn.cursor() eventKey = input("Event key: ") tba = tbapy.TBA(TBAkey) try: matchlistRaw = tba.event_matches(eventKey) except: print("Failed to retrieve matches from TBA") exit(1) for i in range(len(matchlistRaw)): if matchlistRaw[i].comp_level == "qm": if matchlistRaw[i].winning_alliance == "red": redWon = 1 blueWon = 0 else: redWon = 0 blueWon = 1 cur.execute("UPDATE scout SET WonMatch=? WHERE Match=? AND AllianceColor=?", (redWon, matchlistRaw[i].match_number, 0))
def __init__(self, auth_key): self.tba = tbapy.TBA(auth_key)
import tbapy tba = tbapy.TBA( 'DJRE7IGB1IBTCtvpZfFnn7aZfBWoY9bTIZfQFY7CVBZ8tWeNRX6x0XdISQ63skHv') years = [2016, 2017, 2018] cmpData = { '2016': { 'cmpmo': { 'slots': 600, 'districts': { 'chs': 25, 'in': 9, 'fim': 76, 'mar': 22, 'nc': 10, 'ne': 34, 'pnw': 30, 'pch': 12 } } }, '2017': { 'north': { 'slots': 402, 'districts': { 'chs': 23, 'fim': 82, 'in': 10, 'mar': 22, 'ne': 37,
import tbapy import numpy as np from numpy.linalg import inv from sklearn.metrics import brier_score_loss import time import random import tensorflow # never explicitly called, but is a necessary dependency for Keras from keras.models import Sequential, model_from_json from keras.layers import Dense # This is an important switch. Once you train the model on your computer, I'd turn it off, then if you want to # make adjustments to the neural network, you don't have to recalculate the underlying training data data_collection = True # Allows me to access TBA API tba = tbapy.TBA("secret, get your own from https://www.thebluealliance.com/account") # If you've already initialized the model, you can use the np.load line, else you need # To start from a blank team dictionary dict_team_OPRs = {} # dict_team_OPRs = np.load('OPRs_2019.npy').item() # Scrapes data from Caleb Sykes' ELO data into a dictionary dict_team_ELOs = {} ELO_csv = open('C:\\Users\\zglas\\Documents\\2019ELO.csv', "r", encoding='utf-8-sig') for line in ELO_csv: line.strip() team, elo = line.split(",") dict_team_ELOs["frc" + str(team)] = int(elo)
"""This file extracts data using the tbapy library from The Blue Alliance API @author Ujjaini Das """ import tbapy import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from pandas import DataFrame from oct2py import Oct2Py oc = Oct2Py() tba = tbapy.TBA( "MtsQ8UR2BsMQ03giTxFXqNbP61OyHF1Sy9VNNKbK8UjtBfr8NQfYF7Gbs7XrDkoA") event_list = tba.events('2019', keys=True) rankings = tba.event_rankings('2019txdel') df = pd.DataFrame(rankings['rankings']) event_list.remove('2019txdel') for i in event_list: rankings = tba.event_rankings(i) df = pd.concat([df, pd.DataFrame(rankings['rankings'])], axis=0) print(df) losses = [] wins = [] ties = []