├── .gitignore ├── LICENSE ├── Procfile ├── README.md ├── app.json ├── app.py ├── github ├── __init__.py ├── exceptions.py ├── github_api.py ├── github_issue_object.py ├── github_webhook.py └── test_githubIssueObject.py ├── habitica ├── __init__.py ├── exceptions.py ├── habitica_api.py ├── habitica_task.py ├── test_habiticaAPIClient.py └── test_habiticaTask.py ├── handler.py ├── requirements.txt └── runtime.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Daniel Beck 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: python app.py 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/danielbe1/github-rpg) 2 | ==================================================================================================================================== 3 | 4 | This is a little service I've created to make organizing projects more rewarding by turning Github issues to Habitica tasks. 5 | The service is intended to be deployed on the Heroku platform and you can try it by pressing the nice purple button above. 6 | 7 | Service configuration 8 | ===================== 9 | The service requires only 3 configuration settings: 10 | * USER_KEY - The Habitca user key. 11 | * API_KEY - The Habitica API key. 12 | * LABEL_TO_IGNORE - The name of a label that can be applied to issues that you want the service to ignore. 13 | 14 | Setting up the Github repo 15 | ========================== 16 | In your repo webhook settings set the webhook as follows: 17 | * Payload URL - The URL for the heroku application you created. 18 | * Content type - Set this to `application/json` 19 | * Set the webhook events to `Send me everything.` 20 | 21 | Issues <--> Tasks in a nutshell 22 | ============================== 23 | * When opening a new Github issue, a new `todo` task will be created on your Habitica account. 24 | * When closing an existing Github issue, the corresponding Habitica `todo` task will be completed, if the task does not exist it will be recreated. 25 | * When reopening a closed Github issue, the corresponding Habitica `todo` task will be uncompleted, if it does not exist it will be recreated. 26 | 27 | Task hints in Github issues 28 | =========================== 29 | It is possible to specify certain hints on the Github issue to specify task parameters: 30 | * Difficulty: 31 | - `Difficulty: trivial` 32 | - `Difficulty: easy` 33 | - `Difficulty: medium` 34 | - `Difficulty: hard` 35 | 36 | Excluding Github issues 37 | ======================= 38 | Specific issues can be excluded from being synced by adding a label, defined in the `LABEL_TO_IGNORE` env variable (set to `github-rpg-ignore` by default). 39 | Adding or removing this label from existing issues will acuse the corresponding `todo` tasks to be deleted or recreated accordingly. 40 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "github-rpg", 3 | "description": "Create Habitica todo tasks for Github issues and complete them when Complete todo tasks ", 4 | "repository": "https://github.com/danielbe1/github-rpg", 5 | "keywords": [ 6 | "habitrpg", 7 | "habitica", 8 | "github" 9 | ], 10 | "env": { 11 | "USER_KEY": { 12 | "description": "The unique Habitica User ID (https://habitica.com/#/options/settings/api)." 13 | }, 14 | "API_KEY": { 15 | "description": "the secret Habitica API Token (https://habitica.com/#/options/settings/api)." 16 | }, 17 | "LABEL_TO_IGNORE": { 18 | "description": "A label that can be added to Github issues that will cause the service to ignore issues", 19 | "value": "github-rpg-ignore" 20 | } 21 | }, 22 | "buildpacks": [ 23 | { 24 | "url": "heroku/python" 25 | } 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import sys 4 | 5 | from flask import Flask 6 | from flask import request 7 | 8 | from github.github_api import GithubWebhookHandler 9 | from habitica.habitica_api import HabiticaAPIClient 10 | 11 | app = Flask(__name__) 12 | habitica_api_client = HabiticaAPIClient() 13 | github_webhook_handler = GithubWebhookHandler( 14 | habitica_api_client, 15 | os.environ.get('LABEL_TO_IGNORE', 'github-rpg-ignore')) 16 | 17 | 18 | @app.route('/', methods=['POST']) 19 | def handle_github_webhook(): 20 | try: 21 | github_webhook_handler.handle_webhook(request) 22 | except Exception as e: 23 | print(str(e)) 24 | 25 | return 'success' 26 | 27 | if __name__ == '__main__': 28 | logging.basicConfig(stream=sys.stdout, level=logging.INFO) 29 | logging.info('Service starting....') 30 | 31 | port = int(os.environ.get('PORT', 5000)) 32 | app.run(host='0.0.0.0', port=port) 33 | -------------------------------------------------------------------------------- /github/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbe1/github-rpg/39934ace9ba1ba2c41192866cb0e0fd097e7b2be/github/__init__.py -------------------------------------------------------------------------------- /github/exceptions.py: -------------------------------------------------------------------------------- 1 | class GithubWebhookHandlerException(Exception): 2 | ''' 3 | The base class for all github webhook errors. 4 | ''' 5 | 6 | def __init__(self, *args, **kwargs): 7 | Exception.__init__(self, *args, **kwargs) 8 | 9 | 10 | class GithubWebhookMalformedEventError(GithubWebhookHandlerException): 11 | ''' 12 | Thrown when the webhook event is not valid; e.g., missing fields in the event JSON. 13 | ''' 14 | 15 | def __init__(self, event, description): 16 | GithubWebhookHandlerException.__init__(self, f'malformed {event} event: {description}') 17 | 18 | 19 | class GithubWebhookBadRequestError(GithubWebhookHandlerException): 20 | ''' 21 | Thrown when the webhook request is not valid for any reason; e.g., missing headers. 22 | ''' 23 | def __init__(self, description): 24 | GithubWebhookHandlerException.__init__(self, description) -------------------------------------------------------------------------------- /github/github_api.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from github.exceptions import GithubWebhookMalformedEventError 4 | from github.github_issue_object import GithubIssueObject 5 | from github.github_webhook import GithubWebhook 6 | 7 | 8 | class GithubWebhookHandler: 9 | def __init__(self, habitica_api_client, ignored_label=None): 10 | self.habitica_api_client = habitica_api_client 11 | self.ignored_label = ignored_label 12 | 13 | def handle_webhook(self, request): 14 | webhook = GithubWebhook.from_request(request) 15 | 16 | if webhook.event_type == 'issues': 17 | self.handle_issues_event(webhook.body_json) 18 | else: 19 | logging.info(f'unknown event "{webhook.event_type}", skipping') 20 | 21 | def handle_issues_event(self, request_json): 22 | if 'action' not in request_json: 23 | raise GithubWebhookMalformedEventError('issues', 'missing "action" field') 24 | 25 | action = request_json['action'].lower() 26 | issue = GithubIssueObject.from_json(request_json) 27 | 28 | if issue.label_assigned(self.ignored_label) and action == 'labeled': 29 | self.delete_task_if_exists(issue) 30 | elif not issue.label_assigned(self.ignored_label) and action == 'unlabeled': 31 | self.create_task_if_does_not_exists(issue) 32 | elif action == 'opened': 33 | self.handle_issue_opened(issue) 34 | elif action == 'reopened': 35 | self.handle_issue_reopenened(issue) 36 | elif action == 'closed': 37 | self.handle_issue_closed(issue) 38 | elif action == 'edited': 39 | self.handle_issue_edited(issue) 40 | else: 41 | logging.info(f'ignoring unhandled issues action {action}') 42 | 43 | def delete_task_if_exists(self, issue): 44 | logging.info('ignore label is set, task will be deleted if required') 45 | 46 | task = self.habitica_api_client.get_todo_task(issue.alias) 47 | 48 | if task is not None: 49 | self.habitica_api_client.delete_todo_task(issue.alias) 50 | 51 | def create_task_if_does_not_exists(self, issue): 52 | logging.info('ignore label is not set, task will be created if required') 53 | 54 | task = self.habitica_api_client.get_todo_task(issue.alias) 55 | 56 | if task is None: 57 | self.habitica_api_client.create_new_todo_task(issue.alias, issue.title, issue.habitica_task_difficulty) 58 | 59 | def handle_issue_opened(self, issue): 60 | logging.info(f'issue {issue.number} titled "{issue.title}" opened') 61 | 62 | self.habitica_api_client.create_new_todo_task(issue.alias, issue.title, issue.habitica_task_difficulty) 63 | 64 | def handle_issue_reopenened(self, issue): 65 | logging.info(f'issue {issue.number} titled "{issue.title}" reopened') 66 | 67 | self.habitica_api_client.uncomplete_todo_task(issue.alias, issue.title, issue.habitica_task_difficulty) 68 | 69 | def handle_issue_closed(self, issue): 70 | logging.info(f'issue {issue.number} titled "{issue.title}" closed') 71 | 72 | self.habitica_api_client.complete_todo_task(issue.alias, issue.title, issue.habitica_task_difficulty) 73 | 74 | def handle_issue_edited(self, issue): 75 | logging.info(f'issue {issue.number} titled "{issue.title}" edited') 76 | 77 | self.habitica_api_client.update_todo_task(issue.alias, issue.title, issue.habitica_task_difficulty) 78 | -------------------------------------------------------------------------------- /github/github_issue_object.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | from github.exceptions import GithubWebhookMalformedEventError 4 | from habitica.habitica_task import HabiticaTask 5 | 6 | 7 | class GithubIssueObject: 8 | def __init__(self, number, repo_id, title, body, labels): 9 | self.github_repo_id = repo_id 10 | self.number = number 11 | self.title = title 12 | self.body = body 13 | self.labels = labels 14 | self.alias = self.get_task_alias(number, repo_id) 15 | self.habitica_task_difficulty = self.get_difficulty(body) 16 | 17 | @staticmethod 18 | def from_json(js): 19 | if 'issue' not in js: 20 | raise GithubWebhookMalformedEventError('issues', 'missing "issue" object') 21 | elif 'number' not in js['issue']: 22 | raise GithubWebhookMalformedEventError('issues', 'missing "number" field in issue object') 23 | elif 'title' not in js['issue']: 24 | raise GithubWebhookMalformedEventError('issues', 'missing "title" field in issue object') 25 | elif 'labels' not in js['issue']: 26 | raise GithubWebhookMalformedEventError('issues', 'missing "labels" field in issue object') 27 | elif 'repository' not in js: 28 | raise GithubWebhookMalformedEventError('issues', 'missing "repository" object') 29 | elif 'id' not in js['repository']: 30 | raise GithubWebhookMalformedEventError('issues', 'missing "repository" object') 31 | 32 | return GithubIssueObject( 33 | number = js['issue']['number'], 34 | repo_id= js['repository']['id'], 35 | title = js['issue']['title'], 36 | body = js['issue'].get('body', ''), 37 | labels = map(GithubIssueObject.parse_label, js['issue']['labels'])) 38 | 39 | @staticmethod 40 | def parse_label(json): 41 | if 'name' not in json: 42 | raise GithubWebhookMalformedEventError('issues', 'missing "name" field in label object') 43 | 44 | return json['name'] 45 | 46 | def label_assigned(self, label): 47 | return label in self.labels 48 | 49 | @staticmethod 50 | def get_task_alias(number, github_repo_id): 51 | return f'repo_{github_repo_id}_issue_{number}' 52 | 53 | @staticmethod 54 | def get_difficulty(body): 55 | difficulties = re.findall(r'difficulty:\s*(\w*)', body.lower()) 56 | 57 | if not difficulties: 58 | return HabiticaTask.EASY_TASK 59 | 60 | difficulty = HabiticaTask.string_to_difficulty(difficulties[-1]) 61 | 62 | if difficulty is None: 63 | return HabiticaTask.EASY_TASK 64 | 65 | return difficulty 66 | -------------------------------------------------------------------------------- /github/github_webhook.py: -------------------------------------------------------------------------------- 1 | from github.exceptions import GithubWebhookBadRequestError 2 | 3 | 4 | class GithubWebhook: 5 | def __init__(self, event_type, body_json): 6 | self.event_type = event_type 7 | self.body_json = body_json 8 | 9 | @staticmethod 10 | def from_request(request): 11 | if 'X-GitHub-Event' not in request.headers: 12 | raise GithubWebhookBadRequestError('missing X-GitHub-Event header') 13 | elif request.json is None: 14 | raise GithubWebhookBadRequestError('request body is not a valid JSON') 15 | 16 | event_type = request.headers['X-GitHub-Event'].lower() 17 | 18 | return GithubWebhook(event_type, request.json) 19 | -------------------------------------------------------------------------------- /github/test_githubIssueObject.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from github.github_issue_object import GithubIssueObject 4 | 5 | 6 | class TestGithubIssueObject(TestCase): 7 | def test_get_difficulty(self): 8 | self.assertEqual(GithubIssueObject.get_difficulty('difficulty: trivial'), 0.1, 'difficulty should have been 0.5') 9 | self.assertEqual(GithubIssueObject.get_difficulty('difficulty:easy'), 1, 'difficulty should have been 1') 10 | self.assertEqual(GithubIssueObject.get_difficulty('difficulty: medium'), 1.5, 'difficulty should have been 1.5') 11 | self.assertEqual(GithubIssueObject.get_difficulty('difficulty: hard'), 2, 'difficulty should have been 2') 12 | self.assertEqual(GithubIssueObject.get_difficulty('difficulty: none'), 1, 'difficulty should have been 1') 13 | self.assertEqual(GithubIssueObject.get_difficulty(''), 1, 'difficulty should have been 1') 14 | -------------------------------------------------------------------------------- /habitica/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbe1/github-rpg/39934ace9ba1ba2c41192866cb0e0fd097e7b2be/habitica/__init__.py -------------------------------------------------------------------------------- /habitica/exceptions.py: -------------------------------------------------------------------------------- 1 | class HabiticaCLientException(Exception): 2 | ''' 3 | The base class for all habitica API client errors. 4 | ''' 5 | def __init__(self, *args, **kwargs): 6 | Exception.__init__(self, *args, **kwargs) 7 | 8 | 9 | class HabiticaCLientConfigError(HabiticaCLientException): 10 | ''' 11 | Thrown if configuration for the habitica API client is missing or invalid. 12 | ''' 13 | def __init__(self, description): 14 | HabiticaCLientException.__init__(self, description) 15 | 16 | 17 | class HabiticaCLientConnectivityError(HabiticaCLientException): 18 | ''' 19 | The base class for all habitica API client connectivity errors; e.g., request timeouts. 20 | ''' 21 | def __init__(self, description): 22 | HabiticaCLientException.__init__(self, description) 23 | 24 | 25 | class HabiticaClientTimeoutError(HabiticaCLientConnectivityError): 26 | ''' 27 | Thrown when API calls timeout. 28 | ''' 29 | def __init__(self): 30 | HabiticaCLientConnectivityError.__init__(self, 'habitica API request timed out') 31 | 32 | 33 | class HabiticaClientIllegalResponseError(HabiticaCLientConnectivityError): 34 | ''' 35 | Thrown when the response to an API call cannot be validated as an API response; e.g., the body is not a JSON. 36 | ''' 37 | def __init__(self): 38 | HabiticaCLientConnectivityError.__init__(self, f'illegal response') 39 | 40 | 41 | class HabiticaClientAPIError(HabiticaCLientException): 42 | ''' 43 | The base class for API logical and validation errors. 44 | ''' 45 | def __init__(self, description): 46 | HabiticaCLientException.__init__(self, description) 47 | 48 | 49 | class HabiticaClientHttpStatusCodeError(HabiticaCLientException): 50 | ''' 51 | Thrown when the status code returned after an API call is unexpected. 52 | 53 | Note that 4xx errors are not always unexpected and that 2xx status codes are not always expected, 54 | it depends on the speicifc API call itself. 55 | ''' 56 | def __init__(self, status_code, body): 57 | HabiticaCLientException.__init__(self, f'unexpected status code: {status_code}: {body}') 58 | 59 | self.status_code = status_code 60 | 61 | 62 | class HabiticaClientAPIUnauthorizedError(HabiticaClientAPIError): 63 | ''' 64 | Thrown when the credentials (user and api keys) are missing or invalid. 65 | ''' 66 | def __init__(self, description): 67 | HabiticaCLientConnectivityError.__init__(self, f'unauthorized action: {description}') 68 | 69 | 70 | class HabiticaClientAPIMalformedObjectError(HabiticaClientAPIError): 71 | ''' 72 | Thrown when an API object is invalid; e.g., missing fields in object JSON. 73 | ''' 74 | def __init__(self, obj, description): 75 | HabiticaCLientConnectivityError.__init__(self, f'malformed {obj} object: {description}') 76 | -------------------------------------------------------------------------------- /habitica/habitica_api.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | 4 | import requests 5 | 6 | from habitica.exceptions import * 7 | from habitica.habitica_task import HabiticaTask 8 | 9 | 10 | class HabiticaAPIClient: 11 | ''' 12 | A Habitica API client that deals with todo tasks. 13 | ''' 14 | 15 | def __init__(self): 16 | if 'USER_KEY' not in os.environ: 17 | raise HabiticaCLientConfigError('missing user key configuration') 18 | 19 | if 'API_KEY'not in os.environ: 20 | raise HabiticaCLientConfigError('missing api key configuration') 21 | 22 | self.auth_headers = { 23 | 'x-api-user': os.environ['USER_KEY'], 24 | 'x-api-key': os.environ['API_KEY'] 25 | } 26 | 27 | def get_todo_task(self, alias): 28 | ''' 29 | Gets a task by its alias. 30 | 31 | :param alias: The alias of the task to get. 32 | :return: The task instance if it exists, None otherwise. 33 | ''' 34 | result = self._make_get_api_call(f'https://habitica.com/api/v3/tasks/{alias}', True) 35 | 36 | if 'data' not in result: 37 | return None 38 | 39 | task = HabiticaTask.from_json(result['data']) 40 | 41 | if task.type != 'todo': 42 | return None 43 | 44 | return task 45 | 46 | def create_new_todo_task(self, alias, title, difficulty): 47 | ''' 48 | Create a new todo task. 49 | 50 | :param alias: The alias to create the task with. 51 | :param title: The title to give the new task. 52 | :param difficulty: The difficulty of the new task. 53 | ''' 54 | task = self.get_todo_task(alias) 55 | 56 | if task is not None: 57 | logging.info(f'task "{alias}" already exists, skipping creation') 58 | 59 | return 60 | 61 | request_body = { 62 | 'text': title, 63 | 'type': 'todo', 64 | 'alias': alias, 65 | 'priority': difficulty 66 | } 67 | 68 | logging.info(f'creating task "{alias}"') 69 | 70 | self._make_post_api_call('https://habitica.com/api/v3/tasks/user', request_body) 71 | 72 | def complete_todo_task(self, alias, title=None, difficulty=HabiticaTask.EASY_TASK): 73 | ''' 74 | Sets a todo task as complete, creating it if necessary. 75 | 76 | :param alias: The alias of the task to complete. 77 | :param title: A title to use for creation if a task does not exist, or None to not create it. 78 | :param difficulty: The difficulty to create the task with. 79 | ''' 80 | task = self.get_todo_task(alias) 81 | 82 | if task is None: 83 | if title is not None: 84 | logging.info(f'task "{alias}" did not exist, creating a new one') 85 | 86 | self.create_new_todo_task(alias, title, difficulty) 87 | self.complete_todo_task(alias) 88 | 89 | return 90 | else: 91 | logging.info(f'failed finding task "{alias}", not completing') 92 | 93 | return 94 | elif task.done: 95 | logging.info(f'task "{alias}" already complete, skipping') 96 | 97 | return 98 | 99 | logging.info(f'completing task "{alias}"') 100 | request_body = {} 101 | self._make_post_api_call(f'https://habitica.com/api/v3/tasks/{task.id}/score/up', request_body) 102 | 103 | def uncomplete_todo_task(self, alias, title=None, difficulty=HabiticaTask.EASY_TASK): 104 | ''' 105 | Sets a todo task as uncomplete, creating it if necessary. 106 | 107 | :param alias: The alias of the task to uncomplete. 108 | :param title: A title to use for creation if a task does not exist, or None to not create it. 109 | :param difficulty: The difficulty to create the task with. 110 | ''' 111 | task = self.get_todo_task(alias) 112 | 113 | if task is None: 114 | if title is not None: 115 | logging.info(f'task "{alias}" did not exist, creating a new one') 116 | 117 | self.create_new_todo_task(alias, title, difficulty) 118 | 119 | return 120 | else: 121 | logging.info(f'failed finding task "{alias}", not uncompleting') 122 | 123 | return 124 | elif not task.done: 125 | logging.info(f'task "{alias}" already uncomplete, skipping') 126 | 127 | return 128 | 129 | logging.info(f'uncompleting task "{alias}"') 130 | request_body = {} 131 | self._make_post_api_call(f'https://habitica.com/api/v3/tasks/{task.id}/score/down', request_body) 132 | 133 | def delete_todo_task(self, alias): 134 | ''' 135 | Delete a todo task, if the task does not exist, nothing will be changed. 136 | 137 | :param alias: The alias of the task to delete. 138 | ''' 139 | task = self.get_todo_task(alias) 140 | 141 | if task is None: 142 | logging.info(f'failed finding task "{alias}", not deleting') 143 | 144 | return 145 | 146 | logging.info('deleting task') 147 | self._make_delete_api_call(f'https://habitica.com/api/v3/tasks/{alias}') 148 | 149 | def update_todo_task(self, alias, text=None, priority=None): 150 | ''' 151 | Updates a todo task details. 152 | 153 | :param alias: The alias of the task to update. 154 | :param text: The title to update, or None to not update it. 155 | :param priority: The priority to update, or None to not update it. 156 | ''' 157 | request_body = {} 158 | 159 | if text is not None: 160 | request_body['text'] = text 161 | if priority is not None: 162 | request_body['priority'] = priority 163 | 164 | logging.info('updating task') 165 | self._make_put_api_call(f'https://habitica.com/api/v3/tasks/{alias}', request_body) 166 | 167 | def _make_post_api_call(self, url, body_dictionary, allow_unknown_resource=False): 168 | headers = { 'Content-Type': 'application/json' } 169 | headers.update(self.auth_headers) 170 | 171 | response_json = self._validate_request(lambda: requests.post(url, json=body_dictionary, headers=headers), allow_unknown_resource) 172 | 173 | return response_json 174 | 175 | def _make_get_api_call(self, url, allow_unknown_resource=False): 176 | response_json = self._validate_request(lambda: requests.get(url, headers=self.auth_headers), allow_unknown_resource) 177 | 178 | return response_json 179 | 180 | def _make_put_api_call(self, url, body_dictionary): 181 | response_json = self._validate_request(lambda: requests.put(url, json=body_dictionary, headers=self.auth_headers), True) 182 | 183 | return response_json 184 | 185 | def _make_delete_api_call(self, url): 186 | response_json = self._validate_request(lambda: requests.delete(url, headers=self.auth_headers), True) 187 | 188 | return response_json 189 | 190 | def _validate_request(self, request_lambda, missing_resource_allowed): 191 | try: 192 | response = request_lambda() 193 | status_code = response.status_code 194 | response_json = response.json() 195 | except requests.exceptions.Timeout: 196 | raise HabiticaClientTimeoutError() 197 | except (requests.exceptions.RequestException, ConnectionError) as e: 198 | raise HabiticaCLientConnectivityError(f'unknown error: {str(e)}') 199 | except ValueError: 200 | raise HabiticaClientIllegalResponseError() 201 | else: 202 | self._validate_status_code(status_code, response_json, missing_resource_allowed) 203 | 204 | return response_json 205 | 206 | def _validate_status_code(self, status_code, response_json, missing_resource_allowed): 207 | if str(status_code)[0] == '2' and 'success' in response_json and response_json['success']: 208 | return 209 | elif missing_resource_allowed and status_code == 404 and 'error' in response_json and response_json['error'] == 'NotFound': 210 | return 211 | else: 212 | raise HabiticaClientHttpStatusCodeError(status_code, response_json) 213 | -------------------------------------------------------------------------------- /habitica/habitica_task.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from habitica.exceptions import HabiticaClientAPIMalformedObjectError 4 | 5 | 6 | class HabiticaTask: 7 | TRIVIAL_TASK = 0.1 8 | EASY_TASK = 1 9 | MEDIUM_TASK = 1.5 10 | HARD_TASK = 2 11 | 12 | def __init__(self, alias, task_id, done, difficulty, task_type): 13 | self.alias = alias 14 | self.id = task_id 15 | self.done = done 16 | self.difficulty = difficulty 17 | self.type = task_type 18 | 19 | @staticmethod 20 | def from_json(js): 21 | if type(js) is str: 22 | js = json.loads(js) 23 | 24 | if 'alias' not in js: 25 | raise HabiticaClientAPIMalformedObjectError('task', 'missing "alias" field') 26 | elif 'id' not in js: 27 | raise HabiticaClientAPIMalformedObjectError('task', 'missing "id" field') 28 | elif 'completed' not in js: 29 | raise HabiticaClientAPIMalformedObjectError('task', 'missing "completed" field') 30 | elif 'priority' not in js: 31 | raise HabiticaClientAPIMalformedObjectError('task', 'missing "priority" field') 32 | elif 'type' not in js: 33 | raise HabiticaClientAPIMalformedObjectError('task', 'missing "type" field') 34 | 35 | return HabiticaTask(js['alias'], js['id'], js['completed'], js['priority'], js['type']) 36 | 37 | @staticmethod 38 | def string_to_difficulty(s): 39 | s = s.strip().lower() 40 | 41 | if s == 'trivial': 42 | return HabiticaTask.TRIVIAL_TASK 43 | if s == 'easy': 44 | return HabiticaTask.EASY_TASK 45 | if s == 'medium': 46 | return HabiticaTask.MEDIUM_TASK 47 | if s == 'hard': 48 | return HabiticaTask.HARD_TASK 49 | 50 | return None 51 | 52 | def __eq__(self, other): 53 | if isinstance(other, self.__class__): 54 | return self.__dict__ == other.__dict__ 55 | 56 | return NotImplemented 57 | 58 | def __ne__(self, other): 59 | if isinstance(other, self.__class__): 60 | return not self.__eq__(other) 61 | 62 | return NotImplemented 63 | 64 | def __hash__(self): 65 | return hash(tuple(sorted(self.__dict__.items()))) 66 | -------------------------------------------------------------------------------- /habitica/test_habiticaAPIClient.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from httmock import HTTMock, all_requests, response 4 | 5 | from habitica.habitica_api import HabiticaAPIClient 6 | 7 | 8 | class TestHabiticaAPIClient(TestCase): 9 | def test_get_existing_todo_task(self): 10 | get_task_url_path = '/api/v3/tasks/alias' 11 | 12 | @all_requests 13 | def requests_mock(url, request): 14 | if url.path == get_task_url_path: 15 | return '{"success":true,"data":{"_id":"2b774d70-ec8b-41c1-8967-eb6b13d962ba","text":"test task","alias":"alias","type":"todo","priority":1.5,"completed":false,"id":"2b774d70-ec8b-41c1-8967-eb6b13d962ba"}}' 16 | 17 | return '{ "success": false, "NotFound": "The specified task could not be found." }' 18 | 19 | with HTTMock(requests_mock): 20 | task = HabiticaAPIClient().get_todo_task('alias') 21 | self.assertEqual(task.type, 'todo', 'task should be todo') 22 | self.assertFalse(task.done, 'task should be done') 23 | self.assertEqual(task.difficulty, 1.5, 'task difficulty should be 1.5') 24 | self.assertEqual(task.alias, 'alias', 'task alias should be alias') 25 | self.assertEqual(task.id, '2b774d70-ec8b-41c1-8967-eb6b13d962ba', 'task id should be "2b774d70-ec8b-41c1-8967-eb6b13d962ba"') 26 | 27 | def test_get_existing_todo_task(self): 28 | @all_requests 29 | def requests_mock(url, request): 30 | return response(404, '{ "success": false, "error": "NotFound" }') 31 | 32 | with HTTMock(requests_mock): 33 | self.assertIsNone(HabiticaAPIClient().get_todo_task('alias'), 'returned task should be None') 34 | 35 | def test_get_existing_todo_task(self): 36 | @all_requests 37 | def requests_mock(url, request): 38 | return response(404, '{ "success": false, "error": "NotFound" }') 39 | 40 | with HTTMock(requests_mock): 41 | self.assertIsNone(HabiticaAPIClient().get_todo_task('alias'), 'returned task should be None') 42 | -------------------------------------------------------------------------------- /habitica/test_habiticaTask.py: -------------------------------------------------------------------------------- 1 | import json 2 | from json import JSONDecodeError 3 | from unittest import TestCase 4 | 5 | from habitica.exceptions import HabiticaClientAPIMalformedObjectError 6 | from habitica.habitica_task import HabiticaTask 7 | 8 | 9 | class TestHabiticaTask(TestCase): 10 | def test_deserializing_strings_and_jsons(self): 11 | task_from_str = HabiticaTask.from_json('{"alias": "alias", "id": "id", "completed": false, "priority": 1.0, "type": "todo"}') 12 | task_from_json = HabiticaTask.from_json(json.loads('{"alias": "alias", "id": "id", "completed": false, "priority": 1.0, "type": "todo"}')) 13 | 14 | self.assertEqual(task_from_str, task_from_json) 15 | 16 | def test_deserializing(self): 17 | task = HabiticaTask.from_json('{"alias": "alias", "id": "id", "completed": false, "priority": 1.0, "type": "todo"}') 18 | 19 | self.assertEqual(task.type, 'todo', 'task should be todo') 20 | self.assertFalse(task.done, 'task should be done') 21 | self.assertEqual(task.difficulty, 1.0, 'task difficulty should be 1.0') 22 | self.assertEqual(task.alias, 'alias', 'task alias should be alias') 23 | self.assertEqual(task.id, 'id', 'task id should be "2b774d70-ec8b-41c1-8967-eb6b13d962ba"') 24 | 25 | def test_deserializing_errors(self): 26 | self.assertRaises(HabiticaClientAPIMalformedObjectError, HabiticaTask.from_json, '{"id": "id", "completed": false, "priority": 1.0, "type": "todo"}') 27 | self.assertRaises(HabiticaClientAPIMalformedObjectError, HabiticaTask.from_json, '{"alias": "alias", "completed": false, "priority": 1.0, "type": "todo"}') 28 | self.assertRaises(HabiticaClientAPIMalformedObjectError, HabiticaTask.from_json, '{"alias": "alias", "id": "id", "priority": 1.0, "type": "todo"}') 29 | self.assertRaises(HabiticaClientAPIMalformedObjectError, HabiticaTask.from_json, '{"alias": "alias", "id": "id", "completed": false, "type": "todo"}') 30 | self.assertRaises(HabiticaClientAPIMalformedObjectError, HabiticaTask.from_json, '{"alias": "alias", "id": "id", "completed": false, "priority": 1.0}') 31 | self.assertRaises(JSONDecodeError, HabiticaTask.from_json, '{') 32 | 33 | def test_get_difficulty(self): 34 | self.assertEqual(HabiticaTask.string_to_difficulty('trivial'), 0.1, 'difficulty should have been 0.1') 35 | self.assertEqual(HabiticaTask.string_to_difficulty('easy'), 1, 'difficulty should have been 1') 36 | self.assertEqual(HabiticaTask.string_to_difficulty(' medium'), 1.5, 'difficulty should have been 1.5') 37 | self.assertEqual(HabiticaTask.string_to_difficulty('hard '), 2, 'difficulty should have been 2') 38 | -------------------------------------------------------------------------------- /handler.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielbe1/github-rpg/39934ace9ba1ba2c41192866cb0e0fd097e7b2be/handler.py -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==0.10.1 2 | Werkzeug==0.12.2 3 | requests==2.18.3 4 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.6.2 2 | --------------------------------------------------------------------------------