Пример #1
0
    def state(self, device, col="", bri=100):
        # Check if hue is active
        if not self.active:
            return

        # Check if light has been detected on startup
        if device not in self.lights:
            print("Philips HUE Device \"{}\" does not detected".format(device))
            return

        data = {}
        if col:
            # Turn hue light on
            data['on'] = True
            tmp = hex_to_hue(col)
            data['hue'] = tmp[0]
            data['sat'] = tmp[1]
        else:
            # Turn hue light off
            data['on'] = False

        if 'bri' in data:
            data['bri'] = round(bri * 2.54)

        # Send API request to Hue Bridge
        url = "http://{}:80/api/{}/lights/{}/state".format(self.ip, self.token, str(self.lights[device]))
        requests_put(url, data=json_dumps(data), timeout=5)
Пример #2
0
    def put_request(self, endpoint, data: dict):
        url = "http://{}:16021/api/v1/{}/{}".format(self.ip, self.token,
                                                    endpoint)
        try:
            result = requests_put(url, data=json_dumps(data), timeout=1)
        except requests_exceptions.RequestException as e:
            print(e)

        if result.status_code == 403:
            print("Error 403, Bad request")
        elif result.status_code == 401:
            print("Error 401, Not authorized")
        elif result.status_code == 404:
            print("Error 404, Resource not found")
        elif result.status_code == 422:
            print("Error 422, Unprocessible entity")
        elif result.status_code == 500:
            print("Error 500, Internal error")

        return result
Пример #3
0
async def challonge_report(command, msg, user, channel, *args, **kwargs):
    match_parts = {} # Stores active participants
    matches = [] # Stores all the match elements at their root [match_obj, etc] instead of {'match': match_obj, etc}

    params = msg.split(' ') # grab the info from the user
    winner_name = ' '.join(params[1:]) # First parameter should be the score. Everything else is the match winner's name
    
    # if not enough arguments, we end early
    if len(params) < 2:
        raise Exception(bold("Challonge_Report") + ": Not enough arguments. Please provide a score and a winner.")

    async with channel.typing():
        parts, tour_url = await start_challonge(command, msg, channel, kwargs['guild']) # Get all the participants and the tournament URL
        match_get = requests_get(base_url + tour_url + "/matches.json", headers={"User-Agent":"Lizard-BOT"}, auth=(chal_user, api_key), params={'state':'open'}) # Grab all the active matches for the tournament

        # If we get a good response and there are matches (aka the tournament has been started)
        if '200' in str(match_get.status_code) and match_get.json():
            # Grab every participant and get the useful information (display name and id number)
            # Originally grabbed every checked in participant but this caused issues with tournies who had no check in
            for part in parts:
                match_parts.update({part['participant']['display_name'].lower():part['participant']['id']})
            # Adjust the root of the match information and put it in an array
            for match in match_get.json():
                m = match['match']
                matches.append(m)
        else:
            # Error out if there are no active matches or if we can't get a good call to Challonge
            raise Exception(bold("Challonge_Report") + ": Error fetching matches for <{0}>. Is the tournament started?".format(tour_url))

        # Check to make sure the given winner is in the bracket
        if winner_name.lower() not in match_parts:
            raise Exception(bold("Challonge_Report") + ": {0} is not in the tournament".format(bold(winner_name)))

        # Go through every active match to find one with the winner in it
        for match in matches:
            # Check to see if the winner is in the current match that is being looped
            if not (match['player1_id'] == match_parts[winner_name.lower()] or match['player2_id'] == match_parts[winner_name.lower()]):
                # Check if we went through every match
                if match == matches[-1]:
                    # Error out that the player wasn't in any active match
                    raise Exception(bold("Challonge_Report") + ": User: {0} does not have an open match to report".format(winner_name))
                continue

            scores = params[0].split('-') # First parameter should be the score

            # Check that the score was given in the proper format
            if not len(scores) == 2:
                # Error out and show what a score should look like
                raise Exception(bold("Challonge_Report") + ": {0} is not a valid score. Example score: 2-0".format(bold(params[0])))

            try:
                # Check to see if we need to reverse the score since it has to be p1-p2
                # So if the winner is p1 and the score is p2-p1, reverse the order to be p1-p2
                # Or if the winner is p2 and the score is p2-p1, reverse the order to be p1-p2
                if (match['player1_id'] == match_parts[winner_name.lower()] and int(scores[1]) > int(scores[0])) or (match['player2_id'] == match_parts[winner_name.lower()] and int(scores[0]) > int(scores[1])):
                    scores.reverse()
            except:
                # Error out if unable to convert each score into an int e.g. a-b
                raise Exception(bold("Challonge_Report") + ": {0} is not a valid score. Example score: 2-0".format(bold(params[0])))

            # Time to send out the winner and the score
            match_put = requests_put(base_url + tour_url + "/matches/" + str(match['id']) +".json", headers={"User-Agent":"Lizard-BOT"}, auth=(chal_user, api_key), params={'match[winner_id]':match_parts[winner_name.lower()], 'match[scores_csv]':'-'.join(scores)})

            # Check to make sure we get a good response
            if '200' in str(match_put.status_code):
                # Good response. Return that the score was updated
                return "Lizard-BOT reported {0} won {1}!".format(bold(winner_name), bold('-'.join(scores)))
            elif '401' in str(match_put.status_code):
                # Permission error
                raise Exception(bold("Challonge_Report") + ": Lizard-BOT does not have access to the tournament")
            else:
                # Some other challonge error. Print it to console and error with appropriate message
                print(match_put.text)
                raise Exception(bold("Challonge_Report") + ": Unknown Challonge error for <" + tour_url + "> while submitting a match")