Example #1
0
    def join_quest(self):
        """
        If there's an unjoined quest, join it.

        :return: True if a quest was joined.
        """
        self._logger.debug("Checking if a quest can be joined.")
        questdata = get_dict_from_api(
            self._header, "https://habitica.com/api/v3/groups/party")["quest"]
        self._logger.debug("Quest information: %s", questdata)
        if ("key" in questdata and not questdata["active"]
                and (self._header["x-api-user"] not in questdata["members"]
                     or not questdata["members"][self._header["x-api-user"]])):
            self._logger.debug("New quest found")
            try:
                habrequest.post(
                    "https://habitica.com/api/v3/groups/party/quests/accept",
                    headers=self._header)
            # pylint: disable=invalid-name
            except requests.exceptions.HTTPError as e:
                self._logger.error("Quest joining failed: %s", str(e))
                # pylint: disable=raise-missing-from
                raise CommunicationFailedException(str(e))
            self._logger.info("Joined quest %s", questdata["key"])
            return True
        return False
Example #2
0
 def cron(self):
     """
     Run cron.
     """
     habrequest.post("https://habitica.com/api/v3/cron",
                     headers=self._header)
     self._logger.debug("Cron run successful.")
Example #3
0
    def send_private_message(self, to_uid, message):
        """
        Send a private message with the given content to the given user.

        After a message has been successfully sent, the bot ticks its PM
        sending habit.

        :to_uid: Habitica user ID of the recipient
        :message: The contents of the message
        """
        api_url = "https://habitica.com/api/v3/members/send-private-message"
        message_parts = self._split_long_message(message)
        if len(message_parts) > 3:
            raise SpamDetected("Sending {} messages at once is not supported."
                               "".format(len(message_parts)))
        for message_part in message_parts:
            try:
                habrequest.post(api_url,
                                headers=self._header,
                                data={
                                    "message": message_part,
                                    "toUserId": to_uid
                                })
            #  pylint: disable=invalid-name
            except requests.exceptions.HTTPError as e:
                #  pylint: disable=raise-missing-from
                raise CommunicationFailedException(str(e))

        self._habitica_operator.tick_task(PM_SENT, task_type="habit")
Example #4
0
    def tick_task(self, task_text, direction="up", task_type=None):
        """
        Tick a task as done.

        :task_text: A string that should be found in the task name and uniquely
                    identify a single task.
        :direction: Used for ticking habits with plus and minus options.
                    Allowed values are "up" and "down", defaults to "up".
        :task_type: If given, only tasks of that type ("habit"/"daily"/"todo")
                    are considered when looking for a matching task.
        :raises:
            NotFoundException: when a matching task is not found
            CommunicationFailedException: when Habitica answers with non-200
                                          status
        """
        task = self.find_task(task_text, task_type=task_type)

        tick_url = ("https://habitica.com/api/v3/tasks/{}/score/{}"
                    "".format(task["_id"], direction))
        try:
            habrequest.post(tick_url, headers=self._header)
        # pylint: disable=invalid-name
        except requests.exceptions.HTTPError as e:
            # pylint: disable=raise-missing-from
            raise CommunicationFailedException(str(e))
Example #5
0
    def add_to_user(self, header):
        """
        Add the current task to personal tasks of the user.

        :header: Habitica API header.
        """
        habrequest.post("https://habitica.com/api/v3/tasks/user",
                        headers=header,
                        data=self._task_dict())
Example #6
0
    def create_to_challenge(self, challenge_id, header):
        """
        Make the given challenge contain this task.

        :challenge_id: The unique identifier of the challenge.
        :header: Habitica API header
        """
        habrequest.post("https://habitica.com/api/v3/tasks/challenge/{}"
                        "".format(challenge_id),
                        headers=header,
                        data=self._task_dict())
Example #7
0
    def send_group_message(self, group_id, message):
        """
        Send a message with the given content to the given group.

        :group_id: UUID of the recipient group, or 'party' for current party of
                   the bot.
        :message: Contents of the message to be sent
        """
        api_url = "https://habitica.com/api/v3/groups/{}/chat".format(group_id)
        try:
            habrequest.post(api_url,
                            headers=self._header,
                            data={"message": message})
        #  pylint: disable=invalid-name
        except requests.exceptions.HTTPError as e:
            #  pylint: disable=raise-missing-from
            raise CommunicationFailedException(str(e))
        self._habitica_operator.tick_task(GROUP_MSG_SENT, task_type="habit")
Example #8
0
 def clone(self):
     """
     Create a clone of this challenge and return its ID.
     """
     resp = habrequest.post(
         "https://habitica.com/api/v3/challenges/{}/clone"
         "".format(self.id),
         headers=self._header)
     resp.raise_for_status()
     return resp.json()["data"]["id"]
Example #9
0
    def award_winner(self, winner):
        """
        Award the given user as the winner for the challenge.

        :winner: UID of the winner
        """
        response = habrequest.post(
            "https://habitica.com/api/v3/challenges/{}/selectWinner/{}"
            "".format(self.id, winner),
            headers=self._header)
        response.raise_for_status()
Example #10
0
    def add_task(self, taskdata):
        """
        Add a new task to this challenge.

        :taskdata: A dict representing the new task, see
                   https://habitica.com/apidoc/#api-Task-CreateChallengeTasks
                   for keys and their values
        """
        resp = habrequest.post(
            "https://habitica.com/api/v3/tasks/challenge/{}".format(self.id),
            data=taskdata,
            headers=self._header)
        resp.raise_for_status()
Example #11
0
    def create_challenge(self, data):
        """
        Create a new challenge with the given data.

        Keys in the data dict, as presented in Habitica API documentation:
            group: The id of the group to which the challenge belongs
            name: The full name of the challenge
            shortName: A shortened name for the challenge, to be used as a tag.
            summary: A short summary advertising the main purpose of the
                     challenge; maximum 250 characters; if not supplied,
                     challenge.name will be used.
            description: A detailed description of the challenge (optional)
            prize: Number of gems offered as a prize to challenge winner
                   (optional, default 0)

        :returns: Challenge object representing the newly-created challenge
        """
        resp = habrequest.post("https://habitica.com/api/v3/challenges",
                               headers=self._header,
                               data=data)
        resp.raise_for_status()
        challenge_id = resp.json()["data"]["id"]

        return Challenge(self._header, challenge_id)