Esempio n. 1
0
def main():
    with open('creds.json') as f:
        creds = json.loads(f.read())
    challonge.set_credentials(creds['username'], creds['APIKey'])
    tournament_url = creds['tournamentURL']
    first_time_flag = True

    while True:
        tournament = challonge.tournaments.show(tournament_url)
        if first_time_flag:
            print("Awaiting tournament...")
            while tournament["started_at"] == None:
                tournament = challonge.tournaments.show(tournament_url)
                time.sleep(2)
                continue
            first_time_flag = False
            print("Tournament found!")
        if tournament["progress_meter"] == 100:
            print("Tournament is over. Thank you for using.")
            break
        params = get_and_parse_custom_parameters()
        if params["ACPN"].upper() == "TRUE":
            tree = make_next_match_etree_with_custom_parameters(
                tournament, params)
        else:
            tree = make_next_match_etree(tournament)
        print("Matches parsed. Writing to file.")
        tree.write("matches.xml")
        print("Done! Refreshing in 5 seconds.\n")
        time.sleep(5)
Esempio n. 2
0
def loadConfig():
    if config.configExists():
        config.loadConfig()
        challonge.set_credentials(config.config['challonge']['username'],
                                  config.config['challonge']['apiKey'])
    else:
        pass
def new_matchups_from_str(username: str, api_key: str, url: str):
    challonge.set_credentials(username, api_key)
    #so the top n players get a bye, where n is the smallest number s.t. n+t=2^k, where t is the toal number of players, and k is an integer. Or if n = 0, everyone fights in round one.
    subdomain = url[url.find("//")+2:url.find(".")]
    tourney_name = url[url.rfind("/")+1:]
    if subdomain == "challonge":
        query = tourney_name
    else:
        query = subdomain + "-" + tourney_name     

    participants = []
    #make list of participants ordered by seed (which is order api returns)
    for participant in challonge.participants.index(query): #doesn't like this
        participants.append(participant['name'])

    round_one_participants = len(participants) - stupid_func(len(participants))

    round_one_matchups = set()
    round_one_players = participants[(-1*round_one_participants):]
    i = 0 
    j = len(round_one_players)-1
    while i < j:
        player_one = normalize(round_one_players[i])
        player_two = normalize(round_one_players[j])
        if player_two < player_one:
            player_one, player_two = player_two, player_one
        round_one_matchups.add(frozenset([player_one, player_two]))
        i+=1
        j-=1

    return round_one_matchups
    def __init__(self, socketId, parent=None):
        super(tournamentServerThread, self).__init__(parent)

        self.log = logging.getLogger(__name__)

        self.app = None

        challonge.set_credentials(CHALLONGE_USER, CHALLONGE_KEY)

        self.socket = QtNetwork.QTcpSocket(self)
        self.socket.setSocketDescriptor(socketId)
        self.parent = parent

        if self.socket.state() == 3 and self.socket.isValid():

            self.nextBlockSize = 0

            self.blockSize = 0

            self.socket.readyRead.connect(self.readDatas)
            self.socket.disconnected.connect(self.disconnection)
            #self.socket.error.connect(self.displayError)

            self.parent.db.open()
            self.pingTimer = QtCore.QTimer(self)
            self.pingTimer.start(31000)
            self.pingTimer.timeout.connect(self.ping)
    def __init__(self, socketId, parent=None):
        super(tournamentServerThread, self).__init__(parent)

        self.log = logging.getLogger(__name__)


        self.app = None
        
        challonge.set_credentials(CHALLONGE_USER, CHALLONGE_KEY)
        
        self.socket = QtNetwork.QTcpSocket(self)
        self.socket.setSocketDescriptor(socketId)
        self.parent = parent
        
        if self.socket.state() == 3 and self.socket.isValid():
            
            self.nextBlockSize = 0
    
            self.blockSize = 0   

            self.socket.readyRead.connect(self.readDatas)
            self.socket.disconnected.connect(self.disconnection)

            self.parent.db.open()   
            self.pingTimer = QtCore.QTimer(self)
            self.pingTimer.start(31000)
            self.pingTimer.timeout.connect(self.ping)
Esempio n. 6
0
def tournaments(request):
    if request.method == 'POST':
        form = TournamentForm(request.POST)
        if form.is_valid():
            challonge.set_credentials("moomoomamoo", "ZGhkIWPh05JyAhwmQI1S8BqYBD7DieZsaKPePIYo")
            url = form.cleaned_data['url']
            tournament_data = challonge.tournaments.show(url)
            name = tournament_data["name"]
            description = tournament_data["description"]
            created_at = tournament_data["created-at"]
            newTournament = ChallongeTournament(name=name,description=description,url=url,created_at=created_at,updated_at=created_at)
            newTournament.save()
            tournament_create_data(challonge, url, newTournament, created_at)
            tournament_update_data(datetime.datetime.now())
            #check if url is unqiue and if the tourney is completed
            #newTournament = ChallongeTournament(name=name, url=url, updated_at=updated_at)
            #tournament_update_data()
    else:
        form = TournamentForm()

    tournaments = ChallongeTournament.objects.all().order_by("created_at")
    i=2
    doit=True
    while(doit==True):
        try:
            tournaments.append(tournments[i])
            tournament[i] = None
            i += 3
        except:
            doit=False
    return render(request, 'main/tournaments.html', {'form': form, 'tournaments': tournaments})
Esempio n. 7
0
def login():
    obj = None
    with open(login_path) as f:
        obj = json.load(f)

    challonge_credentials = obj["challonge"]
    challonge.set_credentials(challonge_credentials["username"], challonge_credentials["key"])
Esempio n. 8
0
File: api.py Progetto: timrxd/PR_Gen
def main():

    user = '******'
    key = 'WVcRiQ7UCjMd5JxyGpzXKk7M36KNot2cALXitGSj'
    mid = 'gg1115'
    
    challonge.set_credentials(user, key)
    
    tournament = challonge.tournaments.show(mid)

    # Represented as dicts
    print(tournament["id"]) # 3272
    print(tournament["name"]) # My Awesome Tournament
    print(tournament["started-at"]) # None

    # Retrieve the participants for a given tournament.
    p = challonge.participants.index(tournament["id"])
    print(len(p)) 

    # Get matches
    matches = challonge.matches.index(tournament['id'])

    for m in matches:
        print(find_player(p, m['winner-id'])['name'] + ' <def.> ' +
              find_player(p, m['loser-id'])['name'])

    print("\nend")
Esempio n. 9
0
 def setchallonge_init(self):
     """Init Challonge api."""
     if not self.check_credentials():
         return False
     challonge.set_credentials(self.settings["API_USERNAME"],
                               self.settings["API_KEY"])
     return True
Esempio n. 10
0
def start_compo(request, competition_id):
    competition = get_object_or_404(Competition, pk=competition_id)
    if competition.status == 1:
        try:
            names = []
            teams, users = competition.get_participants()
            if competition.use_teams:
                for team in teams:
                    names.append(team.title)

            else:
                for user in users:
                    names.append(user.username)

            if len(names) < 2:
                messages.error(request, _(u'Too few participants'))
                return redirect(competition)

            if competition.tournament_format is None:
                messages.error(
                    request,
                    _(u'Set competition tournament format before using this feature.'
                      ))
                return redirect(competition)

            if settings.CHALLONGE_INTEGRATION_ENABLED and settings.CHALLONGE_API_USERNAME != '' and \
                    settings.CHALLONGE_API_KEY != '':
                challonge.set_credentials(settings.CHALLONGE_API_USERNAME,
                                          settings.CHALLONGE_API_KEY)
                url = unicode(competition.lan) + unicode(
                    competition.activity) + unicode(int(time.time()))
                url = re.sub('[^0-9a-zA-Z]+', '', url)
                challonge.tournaments.create(
                    competition.activity.title,
                    url,
                    tournament_type=competition.tournament_format)
                challonge.participants.bulk_add(url, names)
                challonge.tournaments.start(url)
                cparticipants = challonge.participants.index(url)

                for part in cparticipants:
                    if not competition.use_teams:
                        par = Participant.objects.get(
                            user__username=part['name'],
                            competition=competition)
                    else:
                        par = Participant.objects.get(team__title=part['name'],
                                                      competition=competition)
                    par.cid = part['id']
                    par.save()
                competition.challonge_url = url
                update_match_list(request, competition)

            competition.status = 3
            competition.save()
            messages.success(request, _(u'Tournament has started.'))
        except Exception:
            messages.error(request, _(u'Something went wrong.'))

    return redirect(competition)
Esempio n. 11
0
 def setUp(self):
     challonge.set_credentials(username, api_key)
     self.t_name = _get_random_name()
     self.ps_names = [_get_random_name(), _get_random_name()]
     self.t = challonge.tournaments.create(self.t_name, self.t_name)
     self.ps = challonge.participants.bulk_add(
         self.t['id'],
         self.ps_names)
Esempio n. 12
0
	def __init__(self, participant_names, participant_ids, tournament_name, game, url=shortuuid.uuid()[:8], tournament_type='double elimination'):
		self.participant_names = participant_names
		self.participant_ids = participant_ids
		self.tournament_name = tournament_name
		self.game = game
		self.url = url
		self.tournament_type = tournament_type
		challonge.set_credentials(config('CHALLONGE_USERNAME'), config('CHALLONGE_API_KEY'))
Esempio n. 13
0
    def test_get_participants(self):
        challonge.set_credentials(self.api_username, self.api_key)
        tournament = challonge.tournaments.show(self.tournament_url)
        participants = challonge.participants.index(tournament["id"])

        test_players = ['DTMP', 'zaxtorp', 'hamroctopus', 'davethecust']
        for player in participants:
            self.assertIn(player['name'], test_players)
Esempio n. 14
0
 def setUp(self):
     challonge.set_credentials(username, api_key)
     self.t_name = _get_random_name()
     self.ps_names = [_get_random_name(), _get_random_name()]
     self.t = challonge.tournaments.create(self.t_name, self.t_name)
     self.ps = challonge.participants.bulk_add(
         self.t['id'],
         self.ps_names)
Esempio n. 15
0
def gen_records(username: str, api_key: str, tournaments: str):
    challonge.set_credentials(username, api_key)

    # Define our set named tuples
    Set = namedtuple("Set", "winner loser t_url")

    player_list = set()

    season_sets = list(
    )  #season sets is a list of (winner,loser, url) tuples. There is one tuple per set, for each set in the list of urls provided.
    (tournament_urls, tournament_queries,
     tournament_names) = normalize_urls(tournaments)
    for i in range(len(tournament_queries)):
        participants = challonge.participants.index(tournament_queries[i])
        matches = challonge.matches.index(tournament_queries[i])

        #create a map of player_id->name since the matches structure below identifies players by their id, not name.
        player_ids = {}
        for participant in participants:
            name = participant['name']
            player_id = participant['id']
            player_ids[player_id] = normalize(name)
        player_list.update(player_ids.values())

        for match in matches:
            winner = player_ids[match['winner_id']]
            loser = player_ids[match['loser_id']]
            season_sets.append(
                Set(winner=winner, loser=loser, t_url=tournament_urls[i]))

    player_list = sorted(player_list, key=str.lower)

    # Initialize an empty record for each player.
    # A record is a defined as a dict mapping a player name to a 2-tuple of 2-tuple: ((wins, [tourney_urls]),(losses, [tourney_urls]))
    #  Player Name =>
    #    - Player 2 Name =>
    #      - Wins, URLs of tournaments
    #      - Losses, URLs of tournaments
    #
    # Using this format makes our data manipulation and walking very simple.

    season_records = {}
    for p in player_list:
        season_records[p] = {}
        for p2 in player_list:
            if p2 == p:
                continue
            season_records[p][p2] = [[0, []], [0, []]]

    for s in season_sets:
        w, l, u = s
        season_records[w][l][0][0] += 1
        season_records[w][l][0][1].append(
            u)  #Is it possible to efficently sort as they're inserted?
        season_records[l][w][1][0] += 1
        season_records[l][w][1][1].append(u)

    return (player_list, season_records)
Esempio n. 16
0
    def setUp(self):
        challonge.set_credentials(username, api_key)
        self.t_name = _get_random_name()

        self.t = challonge.tournaments.create(self.t_name, self.t_name)
        self.p1_name = _get_random_name()
        self.p1 = challonge.participants.create(self.t["id"], self.p1_name)
        self.p2_name = _get_random_name()
        self.p2 = challonge.participants.create(self.t["id"], self.p2_name)
Esempio n. 17
0
    def setUp(self):
        challonge.set_credentials(username, api_key)
        self.t_name = _get_random_name()

        self.t = challonge.tournaments.create(self.t_name, self.t_name)
        self.p1_name = _get_random_name()
        self.p1 = challonge.participants.create(self.t["id"], self.p1_name)
        self.p2_name = _get_random_name()
        self.p2 = challonge.participants.create(self.t["id"], self.p2_name)
Esempio n. 18
0
 def get(self):
   current_user = get_user_from_auth_header(request, api)
   try:
     challonge.set_credentials(current_user.challonge_username, xor_crypt_string(current_user.api_key, decode=True))
     
     tournaments = challonge.tournaments.index()
     return jsonify({'tournaments' : tournaments})
   except HTTPError as e:
     api.abort(401, 'Invalid credentials.')
def maxRounds(tournament):
    challonge.set_credentials(challonge_username, challonge_key)
    maxRound = [1, 1]
    for match in challonge.matches.index(tournament["id"]):
        if match["round"] > 0:
            maxRound[0] = max(maxRound[0], match["round"])
        else:
            maxRound[1] = max(maxRound[1], abs(match["round"]))
    return maxRound
def get_predictions_thread():
    load_dotenv()
    api_key = get_api_key()
    challonge.set_credentials('lstmemery', api_key)

    return challonge.tournaments.show(
        'madness2022', **{
            'include_participants': 1,
            'include_matches': 1,
            'include_predictions': 1
        })
Esempio n. 21
0
 def post(self):
   try:
     # set the credentials for interfacing with challonge
     challonge_username = request.json['challonge_username']
     api_key = request.json['api_key']
     challonge.set_credentials(challonge_username, api_key)
     # index returns a list of the user's tournaments
     tournaments = challonge.tournaments.index()
     return jsonify({'tournaments' : tournaments})
   except HTTPError as e:
     api.abort(401, 'Invalid credentials.')
	def initialize_challonge_data(self):

		challonge.set_credentials(self.username, self.api_key)

		self.tournament = challonge.tournaments.show(self.tournament_url)
		all_players_raw = challonge.participants.index(self.tournament['id'])

		for participant in all_players_raw:
			name = participant['display-name']
			self.participant_ids[participant['id']] = name
			self.all_players.append(name)
Esempio n. 23
0
def complete_match(request, competition, match):
    if settings.CHALLONGE_INTEGRATION_ENABLED and settings.CHALLONGE_API_USERNAME != '' and settings.CHALLONGE_API_KEY != '':
        challonge.set_credentials(settings.CHALLONGE_API_USERNAME, settings.CHALLONGE_API_KEY)
        challonge.matches.update(competition.challonge_url, match.matchid, scores_csv=match.final_score,
                                 winner_id=match.winner.cid)
        match.state = 'complete'
        match.save()
        update_match_list(request, competition)
        if not Match.objects.filter(competition=competition, state='open'):
            competition.status = 4
            challonge.tournaments.finalize(competition.challonge_url)
            competition.save()
async def get_predictions(loop):
    load_dotenv()
    api_key = get_api_key()
    challonge.set_credentials('lstmemery', api_key)

    tourney = await challonge.tournaments.show(
        'madness2022', **{
            'include_participants': 1,
            'include_matches': 1,
            'include_predictions': 1
        })
    print('Done')
Esempio n. 25
0
    def setUp(self):
        self.api_username = os.environ['CHALLONGE_USERNAME']
        self.api_key = os.environ['CHALLONGE_API_KEY']

        challonge.set_credentials(self.api_username, self.api_key)
        self.t = challonge.tournaments.create(
            'AuTO Test Tournament',
            "autoto_" + "".join(random.choice(string.ascii_lowercase)
                                for _ in range(0, 15)))
        self.p1 = challonge.participants.create(self.t['id'], 'DTMP')
        self.p2 = challonge.participants.create(self.t['id'], 'hamroctopus')
        challonge.tournaments.start(self.t['id'])
Esempio n. 26
0
def complete_match(request, competition, match):
    if settings.CHALLONGE_INTEGRATION_ENABELED and settings.CHALLONGE_API_USERNAME != '' and settings.CHALLONGE_API_KEY != '':
        challonge.set_credentials(settings.CHALLONGE_API_USERNAME, settings.CHALLONGE_API_KEY)
        challonge.matches.update(competition.challonge_url, match.matchid, scores_csv=match.final_score,
                                 winner_id=match.winner.cid)
        match.state = 'complete'
        match.save()
        update_match_list(request, competition)
        if not Match.objects.filter(competition=competition, state='open'):
            competition.status = 4
            challonge.tournaments.finalize(competition.challonge_url)
            competition.save()
Esempio n. 27
0
	def __init__(self, user, secretKey, tourneys):
		self.user = user
		self.secretKey = secretKey

		challonge.set_credentials(self.user, self.secretKey)

		self.playerDict = {}
		self.ctourneyCount = Counter()
		self.matchData = {}

		multipool = Pool(8)
		multipool.map(self._get_players, tourneys)
		multipool.map(self._get_matches, tourneys)
Esempio n. 28
0
def finished_matches(flag):
    bracket_url = get_bracket_url()
    file = open('api-key.txt', 'r')
    apikey = file.read()
    file.close()
    # setup pychallonge
    try:
        sendmsg("fetching match results ..")
        challonge.set_credentials("aptmac", apikey)
        tournament = challonge.tournaments.show(get_bracket_id())
        # get response with all participant info
        participants = challonge.participants.index(tournament["id"])
        players = {}
        for participant in participants:
            players[participant["id"]] = participant["display-name"]
        # get the matches with state complete
        matches = challonge.matches.index(tournament["id"])

        # if showing --all matches
        if flag.strip() == '--all':
            sendmsg("\(`O`)/: All completed matches this tournament are:")
            for match in matches:
                if match["state"] == 'complete':
                    score = match["scores-csv"]
                    if ',' in score:
                        scores = score.split(',')
                        score = scores[len(scores) - 1]
                    sendmsg(players[match["player1-id"]].split()[0][::-1] +
                            ' ' + score + ' ' +
                            players[match["player2-id"]].split()[0][::-1])
                    time.sleep(0.5)
        else:
            sendmsg(
                "\(`O`)/: The last 5 completed matches this tournament are:")
            i = 0
            for match in reversed(matches):
                if match["state"] == 'complete':
                    score = match["scores-csv"]
                    if ',' in score:
                        scores = score.split(',')
                        score = scores[len(scores) - 1]
                    sendmsg(players[match["player1-id"]].split()[0][::-1] +
                            ' ' + score + ' ' +
                            players[match["player2-id"]].split()[0][::-1])
                    time.sleep(0.5)
                    i = i + 1
                if i == 5:
                    break
    except:
        sendmsg('Error: something went wrong with challonge :/')
Esempio n. 29
0
    def setUp(self):
        challonge.set_credentials(username, api_key)
        self.t_name = _get_random_name()

        self.t = challonge.tournaments.create(
            self.t_name,
            self.t_name,
            accept_attachments=True)

        self.ps = challonge.participants.bulk_add(
            self.t['id'],
            [_get_random_name(), _get_random_name()])
        challonge.tournaments.start(self.t['id'])
        self.match = challonge.matches.index(self.t['id'])[0]
Esempio n. 30
0
    def setUp(self):
        challonge.set_credentials(username, api_key)
        self.t_name = _get_random_name()

        self.t = challonge.tournaments.create(
            self.t_name,
            self.t_name,
            accept_attachments=True)

        self.ps = challonge.participants.bulk_add(
            self.t['id'],
            [_get_random_name(), _get_random_name()])
        challonge.tournaments.start(self.t['id'])
        self.match = challonge.matches.index(self.t['id'])[0]
Esempio n. 31
0
def start_compo(request, competition_id):
    competition = get_object_or_404(Competition, pk=competition_id)
    if competition.status == 1:
        try:
            names = []
            teams, users = competition.get_participants()
            if competition.use_teams:
                for team in teams:
                    names.append(team.title)

            else:
                for user in users:
                    names.append(user.username)

            if len(names) < 2:
                messages.error(request, 'Too few participants')
                return redirect(competition)

            if competition.tournament_format is None:
                messages.error(request, 'Set competition tournament format before using this feature')
                return redirect(competition)

            if settings.CHALLONGE_INTEGRATION_ENABELED and settings.CHALLONGE_API_USERNAME != '' and \
                    settings.CHALLONGE_API_KEY != '':
                challonge.set_credentials(settings.CHALLONGE_API_USERNAME, settings.CHALLONGE_API_KEY)
                url = unicode(competition.lan) + unicode(competition.activity) + unicode(int(time.time()))
                url = re.sub('[^0-9a-zA-Z]+', '', url)
                challonge.tournaments.create(competition.activity.title, url,
                                             tournament_type=competition.tournament_format)
                challonge.participants.bulk_add(url, names)
                challonge.tournaments.start(url)
                cparticipants = challonge.participants.index(url)

                for part in cparticipants:
                    if not competition.use_teams:
                        par = Participant.objects.get(user__username=part['name'], competition=competition)
                    else:
                        par = Participant.objects.get(team__title=part['name'], competition=competition)
                    par.cid = part['id']
                    par.save()
                competition.challonge_url = url
                update_match_list(request, competition)

            competition.status = 3
            competition.save()
            messages.success(request, 'Tournament has started!')
        except Exception:
            messages.error(request, 'Something went wrong')

    return redirect(competition)
Esempio n. 32
0
    def setUp(self):
        password = generate_password_hash('password')
        test_user = User('testuser', password, '*****@*****.**',
                         'matchuptesting', challonge_api_key)
        self.test_user = test_user

        db.drop_all()
        db.create_all()
        db.session.add(self.test_user)
        db.session.commit()

        valid_credentials = base64.b64encode(b'testuser:password').decode(
            'utf-8')
        response = self.client.post(
            LOGIN_URL, headers={'Authorization': 'Basic ' + valid_credentials})
        returned = json.loads(response.data)
        self.tk_valid_user = returned['token']
        self.headers = {
            'Content-Type': 'application/json',
            'x-access-token': self.tk_valid_user
        }

        challonge.set_credentials(
            self.test_user.challonge_username,
            xor_crypt_string(self.test_user.api_key, decode=True))

        challonge.tournaments.reset(bracket_1_id)
        challonge.tournaments.start(bracket_1_id)

        event_data = {
            'event_name':
            'Test Event',
            'brackets': [{
                'bracket_id': bracket_1_id,
                'number_of_setups': 0
            }, {
                'bracket_id': bracket_2_id,
                'number_of_setups': 0
            }]
        }

        response = self.client.post(EVENT_URL,
                                    json=event_data,
                                    headers=self.headers)
        self.event = Event.query.get(json.loads(response.data)['id'])

        self.matches_available_bracket_1 = challonge.matches.index(
            bracket_1_id, state='open')
        self.match_to_test = self.matches_available_bracket_1[0]
Esempio n. 33
0
def set_challonge_credentials_from_config(config_filename):
    """Sets up your Challonge API credentials from info in a config file.

    Args:
      config_filename: The filename of the config file to read your credentials
                       from.
    Returns:
      True if the credentials were set successfully, False otherwise.
    """
    credentials = safe_parse_challonge_credentials_from_config(config_filename)
    if not credentials:
        return False

    challonge.set_credentials(credentials["user"], credentials["api_key"])
    return True
Esempio n. 34
0
def main():

    if len(sys.argv) < 2:
        print("\n\tUsage:\tpython load_tourney tourney1 tourney2 ...")
        return
    
    user = '******'
    key = 'WVcRiQ7UCjMd5JxyGpzXKk7M36KNot2cALXitGSj'
    challonge.set_credentials(user, key)

    for t in sys.argv[1:]:
        p = challonge.participants.index(t)
        matches = challonge.matches.index(t)
        for m in matches:
            print(clean(find_player(p, m['winner-id'])['name']) + '\t<def>\t' +
                  clean(find_player(p, m['loser-id'])['name']))
Esempio n. 35
0
 async def challonge_background_task(self):
     # this background task is for showing updates from your tournament
     await self.bot.wait_until_ready()
     challonge.set_credentials("InkxtheSquid", self.bot.challongekey)
     challongeurls = load_challonge_urls()
     channel = discord.utils.get(self.bot.get_all_channels(), name='tournyupdates')
     server = channel.server # I hope this works
     while not self.bot.is_closed:
         url = challongeurls[server.id]["url"]
         tournament = challonge.tournaments.show(url)
         participants = challonge.participants.index(tournament["id"])
         number = len(participants)
         name = (tournament["name"])
         signup = (tournament["sign-up-url"])
         await self.bot.send_message(channel, "**{1}** \n teams/players participating in this tournament: {0} \n signup link: {2}".format(number, name, signup))
         await asyncio.sleep(1800) #runs every 30 mins
Esempio n. 36
0
def tournament_details(request, id):
    updated_at = datetime.datetime.now()
    try:
        # Tell pychallonge about your [CHALLONGE! API credentials](http://api.challonge.com/v1).
        challonge.set_credentials("moomoomamoo", "ZGhkIWPh05JyAhwmQI1S8BqYBD7DieZsaKPePIYo")
        tournament_data = challonge.tournaments.show(id)
        sync = True
    except:
        # couldn't sync to challonge
        sync = False
    try:
        tournament = ChallongeTournament.objects.get(url=id)
        if sync == True and tournament.updated_at < parser.parse(tournament_data["updated-at"]):#,"YYYY-MM-DDThh:mm:ssTZD"):
            tournament.name=tournament_data["name"]
            tournament.updated_at = updated_at
            tournament.save()
            if tournament_update_data(updated_at):
                upToDate = True
            else:
                upToDate = False
    except ChallongeTournament.DoesNotExist:
        #should just 404
        moo="moo"
    playerSyncs = PlayerSync.objects.filter(tournament=tournament).order_by("final_ranking")

    if request.method == 'POST':
        PlayerSyncFormSet = formset_factory(PlayerSyncForm, extra = playerSyncs.count())
        playerSyncFormSet = PlayerSyncFormSet(request.POST, request.FILES)
        if playerSyncFormSet.is_valid():
            for (p, form) in zip(playerSyncs, playerSyncFormSet):
                try: 
                    p.player = form.cleaned_data['playerChoice']
                    p.save()
                except KeyError:
                    p.player = None
                    p.save()
                p.form = form
            tournament_update_data(updated_at)
    else:
        PlayerSyncFormSet = formset_factory(PlayerSyncForm, extra = playerSyncs.count())
        playerSyncFormSet = PlayerSyncFormSet()
        for (p, form) in zip(playerSyncs, playerSyncFormSet):
            form.fields["playerChoice"].initial = p.player
            p.form = form
    matches = PlayerMatch.objects.filter(tournament=tournament).order_by("created_at")
    return render(request, 'main/tournament_details.html', {'tournament': tournament, 'playerSyncs': playerSyncs, 'management_form': playerSyncFormSet.management_form})
Esempio n. 37
0
def getTournamentCSV(user, key, subdomain, bracket_id):
    challonge.set_credentials(user, key)

    tournament = challonge.tournaments.show(subdomain + "-" +
                                            bracket_id)  # Tournament link
    tour_date = tournament["name"].split('(')[1].replace("/", "-")[:4]

    participants = challonge.participants.index(tournament["id"])
    players = convertToPlayers(participants)

    matches = challonge.matches.index(tournament["id"])
    winners = fillInPlayers(matches, players)

    # Export data into a .csv file
    writeCSV(players, winners)

    return tour_date
Esempio n. 38
0
def challonge_add_users():
    username = "******"
    api_key = "VeiRWinHgxU3W77ZV2q2L70uTI0BnhNnq68iu8Oo"

    challonge.set_credentials(username, api_key)

    tournament = challonge.tournaments.show("ufy5bx0r")

    tournament_id = tournament["id"]
    tournament_name = tournament["name"]

    pilots_users = CustomUser.objects.filter(user_role=CustomUser.PILOT)
    for user in pilots_users:
        try:
            challonge.participants.create(tournament_id, user.full_name)
        except Exception as e:
            print(type(e), e)
            continue
Esempio n. 39
0
File: data.py Progetto: girffy/mmrl
def fetch_brackets_to_file(challonge_ids, outfile):
    if config.CHALLONGE_USER == None or config.CHALLONGE_API_KEY == None:
        raise Exception("Put your challonge username and api key in config.py")

    all_matches = []
    all_participants = []
    challonge.set_credentials(config.CHALLONGE_USER, config.CHALLONGE_API_KEY)
    for cid in challonge_ids:
        tournament = challonge.tournaments.show(cid)
        matches = challonge.matches.index(cid)
        participants = challonge.participants.index(cid)

        # add some metadata to each challonge match
        for match in matches:
            if match['completed-at'] == None:
                print("WARNING: match %s hasn't been completed; omitting it" %
                      match['id'])
                match['num_games'] = 0
                continue

            # TODO: could do some smarter parsing here but oh well, DQ's can be
            # ignored anyway
            if len(match['scores-csv'].split('-')) > 2:
                match['num_games'] = 0
                continue
            scores = list(map(int, match['scores-csv'].split('-')))

            match['player1_score'] = scores[0]
            match['player2_score'] = scores[1]
            match['num_games'] = scores[0] + scores[1]

        all_matches.extend([m for m in matches if m['num_games'] > 0])
        all_participants.extend(
            [p for p in participants if p not in all_participants])

    all_data = {'matches': all_matches, 'participants': all_participants}

    with open(outfile, 'wb') as fp:
        #json.dump(all_data, fp, indent=2, sort_keys=True, default=str)
        pickle.dump(all_data, fp)

    print(
        "Finished fetching challonge data; %s matches and %s participants written to %s"
        % (len(all_matches), len(all_participants), outfile))
Esempio n. 40
0
def update_match_list(request, competition):
    if settings.CHALLONGE_INTEGRATION_ENABELED and settings.CHALLONGE_API_USERNAME != '' and \
            settings.CHALLONGE_API_KEY != '':
        challonge.set_credentials(settings.CHALLONGE_API_USERNAME, settings.CHALLONGE_API_KEY)
        c_open_matches = challonge.matches.index(competition.challonge_url)
        competition_matches = Match.objects.filter(competition=competition)
        for copen in c_open_matches:
            if competition_matches:
                open_match = Match.objects.get(matchid=str(copen['id']), competition=competition)
            else:
                open_match = Match(matchid=str(copen['id']), competition=competition)
            if open_match.state != 'error':
                open_match.state = copen['state']
            if copen['player1_id']:
                open_match.player1 = Participant.objects.get(competition=competition, cid=copen['player1_id'])
            if copen['player2_id']:
                open_match.player2 = Participant.objects.get(competition=competition, cid=copen['player2_id'])
            open_match.save()
        return Match.objects.filter(competition=competition, state='open')
Esempio n. 41
0
def update_match_list(request, competition):
    if settings.CHALLONGE_INTEGRATION_ENABLED and settings.CHALLONGE_API_USERNAME != '' and \
            settings.CHALLONGE_API_KEY != '':
        challonge.set_credentials(settings.CHALLONGE_API_USERNAME, settings.CHALLONGE_API_KEY)
        c_open_matches = challonge.matches.index(competition.challonge_url)
        competition_matches = Match.objects.filter(competition=competition)
        for copen in c_open_matches:
            if competition_matches:
                open_match = Match.objects.get(matchid=str(copen['id']), competition=competition)
            else:
                open_match = Match(matchid=str(copen['id']), competition=competition)
            if open_match.state != 'error':
                open_match.state = copen['state']
            if copen['player1_id']:
                open_match.player1 = Participant.objects.get(competition=competition, cid=copen['player1_id'])
            if copen['player2_id']:
                open_match.player2 = Participant.objects.get(competition=competition, cid=copen['player2_id'])
            open_match.save()
        return Match.objects.filter(competition=competition, state='open')
Esempio n. 42
0
def old_matchups_from_str(username: str, api_key: str, tournaments: str):
    challonge.set_credentials(username, api_key)

    old_matches = set() #set of tuples of (players set, date string)
    #print(type(old_matches))
    #for line in tournaments.split('\n'):
    for line in tournaments.split(','):
        url = line.strip()
        if url == "":
            continue

        #get the query for challonge API from the user's provided urls
        subdomain = url[url.find("//")+2:url.find(".")]
        tourney_name = url[url.rfind("/")+1:]
        if subdomain == "challonge":
            query = tourney_name
        else:
            query = subdomain + "-" + tourney_name
        tmp_tournament = challonge.tournaments.show(query)
        match_date = tmp_tournament['started_at'].strftime("%b %d, %Y")
        participants = challonge.participants.index(query)
        matches = challonge.matches.index(query)
        
        #create a map of player_id->name since the matches structure below identifies players by their id, not name.
        player_ids = {}
        for participant in participants:
            name = participant['name']
            player_id = participant['id']
            player_ids[player_id] = normalize(name)

        for match in matches:
            #print(match)
            #old_matches.add((frozenset([player_ids[match['player1_id']], player_ids[match['player2_id']]]), match['started_at'].strftime("%b %d, %Y")))
            player_one = normalize(player_ids[match['player1_id']])
            player_two = normalize(player_ids[match['player2_id']])
            if player_two < player_one:
                player_one, player_two = player_two, player_one 
            old_matches.add((frozenset([player_one, player_two]), match_date))


    return old_matches
Esempio n. 43
0
    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.author = self.request.user

        name = obj.name if len(obj.name) < 8 else (obj.name*2)[:8]

        url = hashlib.md5(name.encode('utf-8')).hexdigest()[:8]
        obj.url = "".join([random.choice(c) for c in url])

        username = "******"
        api_key = "VeiRWinHgxU3W77ZV2q2L70uTI0BnhNnq68iu8Oo"

        challonge.set_credentials(username, api_key)
        tournament = challonge.tournaments.create(obj.name, obj.url) #{"started-at": obj.date})
        tournament_id = tournament["id"]

        obj.id = tournament_id

        obj.save()

        return super().form_valid(form)
Esempio n. 44
0
def gen_standings(username: str, api_key: str, tournaments: str):
    challonge.set_credentials(username, api_key)
    tournament_results = []
    (tournament_urls, tournament_queries,
     tournament_names) = normalize_urls(tournaments)
    for query in tournament_queries:
        participants = challonge.participants.index(query)

        results = {}
        for participant in participants:
            name = participant['name']
            rank = participant['final_rank']
            results[normalize(name)] = rank
        tournament_results.append(results)

    players = set()
    for t in tournament_results:
        players.update(t.keys())
    players = sorted(players)

    return (players, tournament_results, tournament_urls, tournament_names)
Esempio n. 45
0
def main():
    #set credentials and the tournament information.
    challonge.set_credentials("eliasingea", "LTQX768N8omoYw2aaRYTn6EyP6yVztkaRjd7TBkQ")
    #show the specific tournament that we would like to get information from
    tournament = challonge.tournaments.show("qt98yh8i")
    tournamentId = tournament["id"]
    #get the information for all the games for the tournament.
    games = challonge.matches.index(tournamentId)
    #get information for all the participants.
    participants = challonge.participants.index(tournament["id"])

    print tournament["id"]
    print tournament["state"]
    file = open("streamedGames.txt", "w")
    #There are the identifiers for the games that will be streamed.
    streamedGames = ['B', 'O', 'G', 'T', 'K', 'W', 'M']
    #This is the call to the function that will give us the names
    #for the next open game to be streamed.
    playerNameOne, playerNameTwo = getPlayers(games, streamedGames, tournamentId)
    #writes the names to a textfile named streamedGames.txt
    file.write(playerNameOne)
    file.write("\n")
    file.write(playerNameTwo)
Esempio n. 46
0
    def setUp(self):
        challonge.set_credentials(username, api_key)
        self.random_name = _get_random_name()

        self.t = challonge.tournaments.create(self.random_name, self.random_name)
Esempio n. 47
0
 def test_call(self):
     challonge.set_credentials(username, api_key)
     self.assertNotEqual(challonge.fetch("GET", "tournaments"), '')
Esempio n. 48
0
 def test_set_credentials(self):
     challonge.set_credentials(username, api_key)
     self.assertEqual(api._credentials["user"], username)
     self.assertEqual(api._credentials["api_key"], api_key)
Esempio n. 49
0
import challonge, json
from django.conf import settings
from urllib2 import HTTPError
from celery import task
from threading import Timer

# this is here because it's a global that the challonge tasks require
challonge.set_credentials(settings.CHALLONGE_USERNAME, settings.CHALLONGE_API_KEY)

@task()
def create_tournament(name, url, tournament_type):
    try:
        challonge.tournaments.create(name=name, url=url, tournament_type=tournament_type)
    except Exception, e:
        print e

@task()
def delete_tournament(tournament):
    challonge.tournaments.destroy(tournament=tournament)

@task()
def create_participant(tournament, team):
    challonge.participants.create(tournament=tournament.slugified_name, name=team.name)

@task()
def destroy_participant(tournament, team):
    try:
        for p in challonge.participants.index(tournament=tournament.slugified_name):
            if p['name'] == team.name:
                challonge.participants.destroy(tournament=tournament.slugified_name, participant_id=p['id'])
    except HTTPError, err:
import challonge
import json
import pprint

# Tell pychallonge about your [CHALLONGE! API credentials](http://api.challonge.com/v1).
challonge.set_credentials("JVSalazar", "q3KO6htJ1v8Rr8f8Mwm5ZIZmJ48CqKC1GzwDUQM8")

# Retrieve a tournament by its id (or its url).
tournament = challonge.tournaments.show('ceogaming-2015_melee_final')

# Tournaments, matches, and participants are all represented as normal Python dicts.
print(tournament["id"]) # 3272
print(tournament["name"]) # My Awesome Tournament
print(tournament["started-at"]) # None

# Retrieve the participants for a given tournament.
participants = challonge.participants.index(tournament["id"])
participantNames = []

# for name in range (0, 31):
# 	participantNames.append(participants[name]["display-name"])
# 	print(participantNames[name])

for participant in participants:
	print(participant["display-name"])


# # Start the tournament and retrieve the updated information to see the effects
# # of the change.
# challonge.tournaments.start(tournament["id"])
# tournament = challonge.tournaments.show(tournament["id"])
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#-------------------------------------------------------------------------------

import logging

from PySide import QtCore, QtNetwork
from PySide.QtSql import *

from . import tournamentServerThread
from passwords import CHALLONGE_KEY, CHALLONGE_USER
import challonge

challonge.set_credentials(CHALLONGE_USER, CHALLONGE_KEY)



class tournamentServer(QtNetwork.QTcpServer):
    def __init__(self, parent=None):
        super(tournamentServer, self).__init__(parent)
        self.logger = logging.getLogger(__name__)
        self.parent = parent
        self.threads    = []
        self.updaters   = []
        self.db = self.parent.db

        self.tournaments = {}
        self.importTournaments()
        
Esempio n. 52
0
tournament_ids = get_all_tournaments([
    'http://{}.challonge.com/'.format(config.subdomain),
    # 'http://challonge.com/users/' + config.subdomain
])

tournament_ids.append('idnlvvlz')

cached_tournaments = set()

if not os.path.exists(CACHE):
    os.makedirs(CACHE)
else:
    cached_tournaments = set(os.listdir(CACHE))

challonge.set_credentials(config.user, config.api_key)

players = {}
tournaments = {}

for tournament_id in tournament_ids:
    if tournament_id not in cached_tournaments:
        if args.verbose:
            print tournament_id + ': Getting matches'

        matches = challonge.matches.index(tournament_id)
        participants = challonge.participants.index(tournament_id)

        with open(os.path.join(CACHE, tournament_id), 'w') as f:
            json.dump({'matches': matches, 'participants': participants}, f, default=json_serial)
    else:
import challonge
from operator import itemgetter, attrgetter, methodcaller

# Tell pychallonge about your [CHALLONGE! API credentials](http://api.challonge.com/v1).
challonge.set_credentials("Timepilotchkn", "dYDXkiKtJQMBekM6RQntuesUGWwc3nTlslME5FLv")

# Retrieve a tournament by its id (or its url).
tournament = challonge.tournaments.show("FBGT14")

# Tournaments, matches, and participants are all represented as normal Python dicts.
print(tournament["id"]) # 3272
print(tournament["name"]) # My Awesome Tournament
print(tournament["started-at"]) # None

# Retrieve the participants for a given tournament.
participantsData = challonge.participants.index(tournament["id"])
matchData = challonge.matches.index(tournament["id"])
#print(matchData[0])


#---------------------------------------------------------- Player Class

class Player:
    def __init__(self, tagData, playerID, placing):
        self.tag = tagData
        self.ids = [playerID]
        self.place = placing
        if placing == 32:
            self.points = 400
        elif placing == 33:
            self.points = 0
Esempio n. 54
0
 def test_set_credentials(self):
     challonge.set_credentials(username, api_key)
     self.assertEqual(challonge.api._credentials['user'], username)
     self.assertEqual(challonge.api._credentials['api_key'], api_key)
Esempio n. 55
0
    def __init__(self,
                 challonge_tournament_name,
                 api_token='xoxb-15050499792-qRGSf7w5Qv0Eitp7XMoC8w39',
                 slack_username="******",
                 slack_icon_url='http://i.imgur.com/GlnLNWg.jpg',
                 challonge_api_key='ubxCn7J3myaGWsYLeFliIIFD53HhUJQZdgUOlEvY',
                 challonge_username='******',
                 develop=False,
                 no_websocket=False):

        self.logger = logging.getLogger('foosbotson.FoosBotson')
        self.develop = develop

        self.slack = Slacker(api_token)
        self.slack_default_username = slack_username
        self.slack_default_icon_url = slack_icon_url
        self.nick_slack_id = 'U0EFNV9SN'

        self.challonge_tournament_name = challonge_tournament_name
        self.tournament_name = 'amadeus-%s' % challonge_tournament_name
        self.logger.info("Connecting to tournament with id %s" % self.tournament_name)

        challonge.set_credentials(challonge_username, challonge_api_key)
        self.tournament = challonge.tournaments.show(self.tournament_name)
        self.participants = challonge.participants.index(self.tournament_name)
        self.matches = challonge.matches.index(self.tournament_name)

        # The stage must be started manually - so annoy myself here until I do it
        reminders = 0
        while reminders < 5 and not self.find_group_stage_ids():
            self.logger.debug('Sleeping for 30 seconds while waiting for id map')
            self.post_direct_message("(Reminder %i of 5) Start the Group Stage Dumb Dumb :foosball: :snoop:" %
                                     reminders)
            reminders += 1
            time.sleep(30)

        if not no_websocket:
            self.menu_options = {
                'help': {
                    'help_text': 'Display help menu',
                    'detailed_help_text': 'Usage: help [option]\nGet help with a specific menu option',
                    'callable': self.menu_help_text,
                },
                'gloat': {
                    'help_text': 'Gloat about a non-tournament game',
                    'detailed_help_text': 'Gloat about a non-tournament game',
                    'callable': self.menu_gloat,
                },
                'change_name': {
                    'help_text': 'Change the name of your team in a tournament',
                    'detailed_help_text': 'Change the name of your team in a tournament',
                    'callable': self.menu_help_text,
                },
                'generate_teams': {
                    'help_text': 'Generate Teams for a tournament',
                    'detailed_help_text': 'Generate teams for a tournament',
                    'callable': self.menu_help_text,
                }
            }

            # Start the real time messaging
            import websocket
            r = self.slack.rtm.start()
            self.websocket_url = r.body["url"]
            self.logger.info("Websocket URL: %s" % self.websocket_url)

            websocket.enableTrace(True)
            ws = websocket.WebSocketApp(self.websocket_url,
                                        on_message=self.on_message,
                                        on_error=self.on_error,
                                        on_close=self.on_close,
                                        on_open=self.on_open)
            ws.run_forever()
Esempio n. 56
0
def configure():
    challonge.set_credentials(api_email, api_key)
Esempio n. 57
0
import challonge
import elo
from os import environ

username=environ.get("CHALLONGE_USERNAME", "")
api_key=environ.get("CHALLONGE_API_KEY", "")
assert username != "" and api_key != ""
challonge.set_credentials(username, api_key)

# Who the program should print out scores for
topN = ["Lyme", "Bean", "Fest", "Nook", "Couch",
        "Meero", "Ai", "Justin", "Succulent"]

class PlayerStats(object):
    def __init__(self, rank, player, rating):
        self.rank = rank
        self.player = player
        self.rating = rating

    def to_dict(self):
        return {'rank': self.rank,
                'player': self.player,
                'rating': self.rating}

def fetchdemo():
    return [PlayerStats(1, "Lyme", 1250),
            PlayerStats(2, "Bean", 1100),
            PlayerStats(3, "Chump", 1000)]

def fetch():
    ratings = dict()
Esempio n. 58
0
def main():
    listPlayers = pickle.load(open("info/players.pickle", "rb"));
    listMatches = pickle.load(open("info/matches.pickle", "rb"));
    ranking = [];
    user = raw_input("Enter your challonge username: "******"uiblis";
    api_key = raw_input("Enter your api_key: ");
    api_key = "GqEWndsdFiH7JhkIc3l6Ezf8eg3VyxHkACjQN5Pa"

    challonge.set_credentials(user, api_key)

    print("Welcome to BetterPR!")

    while True:
        print("");
        print("Choose an option: ");
        print("1) Input a tournament URL ");
        print("2) Add a match ");
        print("3) View players ");
        print("4) Exit ");

        while True:
            choice = raw_input();
            if (choice == "1"):
                url = getURL();
                tournament = loadURL(url);
                print "";
                print "Tournament: " + tournament["name"];
                print "Date:",
                print tournament["started-at"];

                while True:
                    decision = raw_input("Compile data from this tournament? (y/n) ");
                    if (decision == "n"):
                        break;

                    elif (decision == "y"):
                        tourneyPlayers = [];
                        tourneyMatches = [];
                        compileParticipants(url, tourneyPlayers, listPlayers);
                        compileMatches(url, tourneyMatches, tourneyPlayers, tournament, listPlayers, listMatches);

                        listPlayers.sort(key = lambda x: x.rating.mu, reverse = True)
                        break;

                    else:
                        print ("Please enter 'y' or 'n'. ");
                break;

            if (choice == "2"):
                break;

            if (choice == "3"):
                index = 1;
                for player in listPlayers:
                    player.rank = index;
                    index += 1;
                    player.showInfo();
                break;

            if (choice == "4"):
                pickle.dump(listPlayers, open("info/players.pickle", "wb"))
                pickle.dump(listMatches, open("info/matches.pickle", "wb"))
                exit();

            else:
                print "Please choose a valid option."