Giter VIP home page Giter VIP logo

pychallonge's Introduction

pychallonge

image

Pychallonge provides python bindings for the CHALLONGE! API. The pychallonge module was created by Russ Amos

pychal

Pychal was a fork of pychallonge. The pychal module has been merged into the pychallonge. If you are still using pychal you have to migrate to pychallonge because it is not longer maintained

Requirements

  • iso8601
  • tzlocal
  • pytz
  • requests

Python version support

  • 2.7
  • 3.4+

Installation

For the stable version

pip install pychallonge

For latest development

pip install -e git+http://github.com/ZEDGR/pychallonge#egg=pychallonge

Usage

import challonge

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

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

# 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"])
print(len(participants)) # 13

# 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"])
print(tournament["started_at"]) # 2011-07-31 16:16:02-04:00

See challonge.com for full API documentation.

API Issues

The Challonge API has some issues with the attachments endpoints. The create and update endpoints are not working correctly. When you try to upload an attachment with asset(file) the API returns 500 internal server error. The same happens with asset + description. This issue has been reported to Challonge.

Another issue is the check in process has strange behaviour. When you undo check in a participant the field 'checked_in' remains True but in the website the participant is correctly not checked in. That's why the module does not have any tests on this.

Fixed by pychallonge: In the datetime fields the api returns random timezone offsets, pychallonge convert those to your machine's local time. Also you can set any timezone you want with set_timezone function.

Running the unit tests

Pychallonge comes with a set of unit tests. The tests are not comprehensive, but do utilize each method and verify basic functionality.

In order to test behavior of the python bindings, API calls must be made to CHALLONGE!, which requires a username and api key. To run the tests with your credentials, set CHALLONGE_USER and CHALLONGE_KEY appropriately in your environment.

$ git clone http://github.com/ZEDGR/pychalllonge pychallonge
$ CHALLONGE_USER=my_user CHALLONGE_KEY=my_api_key python pychal/tests.py
...............................
----------------------------------------------------------------------
Ran 31 tests in 98.176s

OK

Note that several tournaments are created, published, started, and completed over the course of the unit tests. These should be cleaned up by the end, but if any of the tests fail they may not be cleaned up. As long as the basic functions work, you can clean up errant tournaments as follows.

import challonge
challonge.set_credentials("my_user", "my_api_key")
for t in challonge.tournaments.index():
    if t["name"].startswith("pychal"):
        challonge.tournaments.destroy(t["id"])

pychallonge's People

Contributors

binury avatar gradymoran avatar oddballbutler avatar russ- avatar russellvt avatar trew avatar zedgr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pychallonge's Issues

cannot import pychallonge

I get the following error in my script while trying to run on a Raspberry pi:

Traceback (most recent call last):
File "Challonge Ticker.py", line 11, in
import pychallonge
ImportError: No module named pychallonge

I've installed pychallonge using pip install pychallonge

I'm trying to modify the following for use on my raspberry pi, but it keeps failing saying p1 = challonge.participants.show(tournamentURL, currentMatch["player1-id"])["name"]; KeyError: 'player1-id'

 `# Carmen "Beanwolf" Condeluci
 # 7/10/14

 from __future__ import print_function
 from shutil import move
 import challonge
 import sys
 import time
 import os
 import dateutil
 import pychallonge'

 print("Barebones Challonge Match Ticker Utility, ver 1.00")
 print("Made by Carmen \"Beanwolf\" Condeluci, most recent build published on 7/10/2014.\n")'

 print("This program pulls recently completed and/or upcoming matches from your Challonge hosted tournament and outputs a summary of the match to a text file. This can then be used with either OBS or XSplit's internal text scrolling tools, or an HTML/Flash source that can process text from and external file.\n")

 print("This file is saved as \"output.txt\" in the same directory as this program.")
 print("It will not appear until after one iteration has completed.\n")

 print("The number of completed and upcoming matches that will fit on the standard XSplit or OBS text scrolls is not too much. OBS, for example, tops out after about 4 completed matchs and 2 upcoming matches with a normal size font and some leading text. Keep this in consideration when working with these utilities.\n")

  challongeUsername = "MYUSERNAME"
  challongeAPIKey = "MYAPIKEY"

 challonge.set_credentials(challongeUsername, challongeAPIKey)

 # Retrieve a tournament by its id (or its url).
 tournamentURL = raw_input("\nPlease enter the tournament's URL indentifier.\n(\"challonge.com/xzr2pwvh\" would have a URL indentifier of \"xzr2pwvh\"): \n")

 tournament = challonge.tournaments.show(tournamentURL)

 matchesToShow = int(raw_input("\nEnter the number of completed matches you would like to show: "))
 upcomingToShow = int(raw_input("\nEnter the number of upcoming matches you would like to show: "))

 leadingText = raw_input("\nEnter any leading text that you would like to have on your ticker: \n")

 # Tournaments, matches, and participants are all represented as normal Python dicts.

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

 print("\nThe program will now start in 5 seconds. It will continue to update indefinitely every minute until manually stopped with Ctrl + C.")
 time.sleep(5);

 #Overall loop would begin here
 while True:

print("Starting an interation...")

output = open('output.txt.tmp', 'w')

output.write(leadingText)

#shows user controlled amount of completed matches (higher rounds first)

output.write("  <|>  Most Recent Completed Matches:  ")

completedMatches = challonge.matches.index(tournament["id"], state="complete")
comLength = len(completedMatches)

# print(completedMatches)

if matchesToShow > comLength:
	for x in range(comLength, 0, -1):
		if x != comLength:
			output.write(" | ")

		currentMatch = completedMatches[x-1]

		comRound = str(currentMatch["round"])
		if "-" not in comRound:
			comRoundString = "W" + comRound
		else:
			comRoundString = "L" + comRound[1:]

		p1 = challonge.participants.show(tournamentURL, currentMatch["player1-id"])["name"];
		p2 = challonge.participants.show(tournamentURL, currentMatch["player2-id"])["name"]
		output.write(comRoundString + ": " + p1 + " vs. " + p2 + ", " + currentMatch["scores-csv"])
else:
	for x in range(comLength, (comLength - matchesToShow), -1):
		if x != comLength:
			output.write(" | ")

		currentMatch = completedMatches[x-1]

		comRound = str(currentMatch["round"])
		if "-" not in comRound:
			comRoundString = "W" + comRound
		else:
			comRoundString = "L" + comRound[1:]

		p1 = challonge.participants.show(tournamentURL, currentMatch["player1-id"])["name"];
		p2 = challonge.participants.show(tournamentURL, currentMatch["player2-id"])["name"]
		output.write(comRoundString + ": " + p1 + " vs. " + p2 + ", " + currentMatch["scores-csv"])

#Shows upcoming matches

output.write("  <|>  Upcoming Matches:  ")

pendingMatches = challonge.matches.index(tournament["id"], state="open")
pendLength = len(pendingMatches)

# print(pendingMatches)

if upcomingToShow > pendLength:
	for x in range(pendLength, 0, -1):
		if x != pendLength:
			output.write(" | ")

		pendingMatch = pendingMatches[x-1]

		penRound = str(pendingMatch["round"])
		if "-" not in penRound:
			penRoundString = "W" + penRound
		else:
			penRoundString = "L" + penRound[1:]

		p1 = challonge.participants.show(tournamentURL, pendingMatch["player1-id"])["name"];
		p2 = challonge.participants.show(tournamentURL, pendingMatch["player2-id"])["name"]
		output.write(penRoundString + ": " + p1 + " vs. " + p2)
else:
	for x in range(pendLength, (pendLength - upcomingToShow), -1):
		if x != pendLength:
			output.write(" | ")

		pendingMatch = pendingMatches[x-1]

		penRound = str(pendingMatch["round"])
		if "-" not in penRound:
			penRoundString = "W" + penRound
		else:
			penRoundString = "L" + penRound[1:]

		p1 = challonge.participants.show(tournamentURL, pendingMatch["player1-id"])["name"];
		p2 = challonge.participants.show(tournamentURL, pendingMatch["player2-id"])["name"]
		output.write(penRoundString + ": " + p1 + " vs. " + p2)

output.write("  <|>  ")

output.close();

move('output.txt.tmp', 'output.txt')

print("Finished an iteration!\n")

time.sleep(60)`

I modified the code from: https://github.com/CCondeluci/Simple-Challonge-Ticker

Any ideas on why this would not be working?

_parse() treats 'misc' as datetime

In api.py the list of string values to treat as text do not include 'misc', which is provided in response to the participant.bulk_add() and index() calls. The API documentation states that 'misc' is user generated string value. Attempts to parse this as a datetime field can alter the fields value.

Ensure every API call has a response

I might be missing something but in all but your GET requests, you don't send back any response. There is still useful information in the response for PUT and POST requests that at the very least would eliminate having to run a second API call to get the information and confirm what you sent.

Also always returning a response at least let's you write error handling if the PUT/POST fails or returns something you don't expect.

ParticipantsTestCase test_update is failing

Since the new update (1.11.1), I have been seeing a FAIL on main.ParticipantsTestCase, now.

Traceback (most recent call last):
  File "tests.py", line 213, in test_update
    self.assertTrue(p1["updated_at"] >= self.ps[0]["updated_at"])
AssertionError: False is not true

I've not yet dug in to it, however.

Tournament participants with all-number names get cast to float type

https://github.com/ZEDGR/pychal/blob/ebefcc8fc05798ce71f1199eb2481a4b99c84608/challonge/api.py#L121

The value of key 'display_name' in the dictionary returned from participants.index() is a float when the tournament participant's name passes float(v) without throwing ValueError. Thus in the returned dictionary every participant's name is of type str except those that can be interpreted as numbers, which are of type float.

FWIW, pychallonge does not have this issue.

502 Bad Gateway

Not entirely sure whats up, but all the sudden I have been getting 502 Bad Gateway

inconsistent timezone

Same program ran twice the timezone is different both times.

[ryan@ryanvile fgc]$ ./get_tournament.py | grep start 'group_stages_were_started': False, 'public_predictions_before_start_time': False, 'start_at': datetime.datetime(2017, 2, 28, 11, 35**, tzinfo=<FixedOffset '-05:00' datetime.timedelta(-1, 68400)>),** 'started_at': datetime.datetime(2017, 2, 28, 11, 43, 51, 214000, **tzinfo=<FixedOffset '-05:00' datetime.timedelta(-1, 68400)>),** 'started_checking_in_at': None, 'group_stages_were_started': False, 'public_predictions_before_start_time': False, 'start_at': datetime.datetime(2017, 2, 28, 13, 30, tzinfo=**<FixedOffset '-05:00' datetime.timedelta(-1, 68400)>),** 'started_at': datetime.datetime(2017, 2, 28, 16, 58, 58, 792000, **tzinfo=<FixedOffset '-05:00' datetime.timedelta(-1, 68400)>),** 'started_checking_in_at': None, 'group_stages_were_started': False, 'public_predictions_before_start_time': False, 'start_at': datetime.datetime(2017, 2, 28, 17, 35, tzinfo=**<FixedOffset '-05:00' datetime.timedelta(-1, 68400)>),** 'started_at': datetime.datetime(2017, 2, 28, 18, 2, 39, 53000, **tzinfo=<FixedOffset '-05:00' datetime.timedelta(-1, 68400)>),** 'started_checking_in_at': None, [ryan@ryanvile fgc]$ ./get_tournament.py | grep start 'group_stages_were_started': False, 'public_predictions_before_start_time': False, 'start_at': datetime.datetime(2017, 2, 28, 17, 35, tzinfo=**<FixedOffset '+01:00' datetime.timedelta(0, 3600)>),** 'started_at': datetime.datetime(2017, 2, 28, 17, 43, 51, 214000, **tzinfo=<FixedOffset '+01:00' datetime.timedelta(0, 3600)>),** 'started_checking_in_at': None, 'group_stages_were_started': False, 'public_predictions_before_start_time': False, 'start_at': datetime.datetime(2017, 2, 28, 19, 30, **tzinfo=<FixedOffset '+01:00' datetime.timedelta(0, 3600)>),** 'started_at': datetime.datetime(2017, 2, 28, 22, 58, 58, 792000, **tzinfo=<FixedOffset '+01:00' datetime.timedelta(0, 3600)>),** 'started_checking_in_at': None, 'group_stages_were_started': False, 'public_predictions_before_start_time': False, 'start_at': datetime.datetime(2017, 2, 28, 23, 35, tzinfo=**<FixedOffset '+01:00' datetime.timedelta(0, 3600)>),** 'started_at': datetime.datetime(2017, 3, 1, 0, 2, 39, 53000, **tzinfo=<FixedOffset '+01:00' datetime.timedelta(0, 3600)>),** 'started_checking_in_at': None,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.