├── requirements.txt ├── webhook_listener ├── version.py └── __init__.py ├── .flake8 ├── .github ├── workflows │ └── release.yml └── FUNDING.yml ├── LICENSE ├── setup.py ├── .gitignore ├── example.py └── README.md /requirements.txt: -------------------------------------------------------------------------------- 1 | cherrypy 2 | -------------------------------------------------------------------------------- /webhook_listener/version.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.2.0" 2 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = E203, E501, W503 3 | exclude = .git,__pycache__,docs,build,dist,logs,.vscode 4 | max-line-length = 88 -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Build & Deploy to PyPI on Release 2 | 3 | on: 4 | release: 5 | types: [released] 6 | 7 | jobs: 8 | deploy: 9 | name: PyPI Deploy 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | - uses: actions/setup-python@v4 14 | - id: dist 15 | uses: casperdcl/deploy-pypi@v2 16 | with: 17 | requirements: twine setuptools wheel 18 | build: true 19 | password: ${{ secrets.PYPI_TOKEN }} 20 | upload: true 21 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [toddrob99] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: ['https://paypal.me/toddrob','https://cash.me/toddrob'] 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 toddrob 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | from distutils.util import convert_path 3 | 4 | # https://stackoverflow.com/questions/2058802/how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package 5 | main_ns = {} 6 | ver_path = convert_path("webhook_listener/version.py") 7 | with open(ver_path) as ver_file: 8 | exec(ver_file.read(), main_ns) 9 | 10 | with open("README.md", "r") as fh: 11 | long_description = fh.read() 12 | 13 | setuptools.setup( 14 | name="Webhook_Listener", 15 | version=main_ns["__version__"], 16 | author="Todd Roberts", 17 | author_email="todd@toddrob.com", 18 | description="Very basic webserver module to listen for webhooks and forward requests to predefined functions.", 19 | long_description=long_description, 20 | long_description_content_type="text/markdown", 21 | url="https://github.com/toddrob99/Webhooks", 22 | packages=setuptools.find_packages(), 23 | install_requires=["cherrypy"], 24 | classifiers=[ 25 | "Programming Language :: Python", 26 | "Programming Language :: Python :: 3", 27 | "License :: OSI Approved :: MIT License", 28 | "Operating System :: OS Independent", 29 | ], 30 | ) 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | logs/ 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | db.sqlite3 60 | 61 | # Flask stuff: 62 | instance/ 63 | .webassets-cache 64 | 65 | # Scrapy stuff: 66 | .scrapy 67 | 68 | # Sphinx documentation 69 | docs/_build/ 70 | 71 | # PyBuilder 72 | target/ 73 | 74 | # Jupyter Notebook 75 | .ipynb_checkpoints 76 | 77 | # pyenv 78 | .python-version 79 | 80 | # celery beat schedule file 81 | celerybeat-schedule 82 | 83 | # SageMath parsed files 84 | *.sage.py 85 | 86 | # Environments 87 | .env 88 | .venv 89 | env/ 90 | venv/ 91 | ENV/ 92 | env.bak/ 93 | venv.bak/ 94 | 95 | # Spyder project settings 96 | .spyderproject 97 | .spyproject 98 | 99 | # Rope project settings 100 | .ropeproject 101 | 102 | # mkdocs documentation 103 | /site 104 | 105 | # mypy 106 | .mypy_cache/ 107 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Webhook Listener Example 3 | 4 | Author: Todd Roberts 5 | 6 | https://github.com/toddrob99/Webhooks 7 | """ 8 | import sys 9 | import os 10 | import logging 11 | import logging.handlers 12 | import time 13 | 14 | import webhook_listener 15 | 16 | import argparse 17 | 18 | parser = argparse.ArgumentParser( 19 | prog="Webhook Listener", description="Start the webhook listener." 20 | ) 21 | parser.add_argument( 22 | "--verbose", "-v", action="store_true", dest="verbose", help="Enable debug logging." 23 | ) 24 | parser.add_argument( 25 | "--port", 26 | "-p", 27 | type=int, 28 | nargs=1, 29 | dest="port", 30 | help="Port for the web server to listen on (default: 8090).", 31 | ) 32 | args = parser.parse_args() 33 | port = args.port[0] if args.port and args.port[0] >= 0 else 8090 34 | 35 | rootLogger = logging.getLogger() 36 | rootLogger.setLevel(logging.DEBUG if args.verbose else logging.INFO) 37 | 38 | logger = logging.getLogger("webhooks") 39 | 40 | console = logging.StreamHandler(sys.stdout) 41 | formatter = logging.Formatter( 42 | "%(asctime)s :: %(levelname)8s :: %(module)s(%(lineno)d) :: %(message)s", 43 | datefmt="%Y-%m-%d %I:%M:%S %p", 44 | ) 45 | console.setFormatter(formatter) 46 | logger.addHandler(console) 47 | 48 | logPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "logs") 49 | if not os.path.exists(logPath): 50 | os.makedirs(logPath) 51 | 52 | file = logging.handlers.TimedRotatingFileHandler( 53 | os.path.join(logPath, "webhooks.log"), when="midnight", interval=1, backupCount=7 54 | ) 55 | file.setFormatter(formatter) 56 | logger.addHandler(file) 57 | logger.debug("Logging started!") 58 | 59 | 60 | def parse_request(request, *args, **kwargs): 61 | logger.debug( 62 | "Received request:\n" 63 | + "Method: {}\n".format(request.method) 64 | + "Headers: {}\n".format(request.headers) 65 | + "Args (url path): {}\n".format(args) 66 | + "Keyword Args (url parameters): {}\n".format(kwargs) 67 | + "Body: {}".format( 68 | request.body.read(int(request.headers["Content-Length"])) 69 | if int(request.headers.get("Content-Length", 0)) > 0 70 | else "" 71 | ) 72 | ) 73 | 74 | # Process the request! 75 | # ... 76 | 77 | return 78 | 79 | 80 | webhooks = webhook_listener.Listener(port=port, handlers={"POST": parse_request}) 81 | webhooks.start() 82 | 83 | while True: 84 | logger.debug("Still alive...") 85 | time.sleep(300) 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Webhook Listener 2 | Very basic webserver module to listen for webhooks and forward requests to predefined functions. 3 | 4 | Author: Todd Roberts 5 | 6 | https://pypi.org/project/webhook_listener/ 7 | 8 | https://github.com/toddrob99/Webhooks 9 | 10 | ## Install 11 | 12 | Install from PyPI using pip 13 | 14 | `pip install webhook_listener` 15 | 16 | ## Use 17 | 18 | * Define a function to process requests 19 | * `request` parameter will be a cherrypy request object 20 | * `*args` parameter will be a tuple of URL path components 21 | * `**kwargs` parameter will be a dictionary of URL parameters 22 | * Get the body of a `POST` request from `request.body.read` passing the length of `request.headers['Content-Length']`: `request.body.read(int(request.headers['Content-Length'])) if int(request.headers.get('Content-Length',0)) > 0 else ''` 23 | * Note: The body will be a byte array, and not a string. You may need to decode it to a string. For example: 24 | ``` 25 | import json 26 | body_raw = request.body.read(int(request.headers['Content-Length'])) if int(request.headers.get('Content-Length',0)) > 0 else '{}' 27 | body = json.loads(body_raw.decode('utf-8')) 28 | ``` 29 | * Include webhook-listener in your project 30 | * Create an instance of the webhook_listener.Listener class 31 | * handlers = Dictionary of functions/callables for each supported HTTP method. (Example: {'POST':process_post_request, 'GET':process_get_request}) 32 | * port = Port for the web server to listen on (default: 8090) 33 | * host = Host for the web server to listen on (default: '0.0.0.0') 34 | * threadPool = Number of worker threads for the web server (default: 10) 35 | * logScreen = Setting for cherrypy to log to screen (default: False) 36 | * autoReload = Setting for cherrypy to auto reload when python files are changed (default: False) 37 | * sslModule = Select which SSL library to use (default: 'builtin') 38 | * sslCert = Path to the certificate (SSL is disabled when empty) 39 | * sslPrivKey = Path to the certificate's private key (SSL is disabled when empty) 40 | * sslCertChain = Path to the full certificate chain 41 | see https://cherrypydocrework.readthedocs.io/deploy.html#ssl-support for more information on SSL support 42 | * Start the Listener 43 | * Keep your application running so the Listener can run in a separate thread 44 | 45 | ## Example 46 | 47 | import time 48 | import webhook_listener 49 | 50 | 51 | def process_post_request(request, *args, **kwargs): 52 | print( 53 | "Received request:\n" 54 | + "Method: {}\n".format(request.method) 55 | + "Headers: {}\n".format(request.headers) 56 | + "Args (url path): {}\n".format(args) 57 | + "Keyword Args (url parameters): {}\n".format(kwargs) 58 | + "Body: {}".format( 59 | request.body.read(int(request.headers["Content-Length"])) 60 | if int(request.headers.get("Content-Length", 0)) > 0 61 | else "" 62 | ) 63 | ) 64 | 65 | # Process the request! 66 | # ... 67 | 68 | return 69 | 70 | 71 | webhooks = webhook_listener.Listener(handlers={"POST": process_post_request}) 72 | webhooks.start() 73 | 74 | while True: 75 | print("Still alive...") 76 | time.sleep(300) 77 | -------------------------------------------------------------------------------- /webhook_listener/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Webhook Listener 3 | 4 | Author: Todd Roberts 5 | 6 | https://github.com/toddrob99/Webhooks 7 | """ 8 | import logging 9 | import cherrypy 10 | import threading 11 | from . import version 12 | 13 | __version__ = version.__version__ 14 | 15 | 16 | class Listener(object): 17 | def __init__(self, *args, **kwargs): 18 | self.logger = logging.getLogger("webhooks") 19 | self.logger.debug("Logging started!") 20 | self.port = kwargs.get("port", 8090) 21 | self.host = kwargs.get("host", "0.0.0.0") 22 | self.threadPool = kwargs.get("threadPool", 10) 23 | self.logScreen = kwargs.get("logScreen", False) 24 | self.autoReload = kwargs.get("autoReload", False) 25 | self.handlers = kwargs.get("handlers", {}) 26 | self.sslModule = kwargs.get("sslModule", "builtin") 27 | self.sslCert = kwargs.get("sslCert", "") 28 | self.sslPrivKey = kwargs.get("sslPrivKey", "") 29 | self.sslCertChain = kwargs.get("sslCertChain", "") 30 | 31 | def start(self): 32 | self.WEBTHREAD = threading.Thread( 33 | target=self._startServer, name="webhooks_websever" 34 | ) 35 | self.WEBTHREAD.daemon = True 36 | self.WEBTHREAD.start() 37 | 38 | def stop(self): 39 | cherrypy.engine.exit() 40 | self.WEBTHREAD = None 41 | 42 | def _startServer(self): 43 | globalConf = { 44 | "global": { 45 | "server.socket_host": self.host, 46 | "server.socket_port": self.port, 47 | "server.thread_pool": self.threadPool, 48 | "engine.autoreload.on": self.autoReload, 49 | "log.screen": self.logScreen, 50 | "server.ssl_module": self.sslModule, 51 | "server.ssl_certificate": self.sslCert, 52 | "server.ssl_private_key": self.sslPrivKey, 53 | "server.ssl_certificate_chain": self.sslCertChain, 54 | } 55 | } 56 | apiConf = { 57 | "/": { 58 | "request.dispatch": cherrypy.dispatch.Dispatcher(), 59 | "tools.response_headers.on": True, 60 | "tools.response_headers.headers": [("Content-Type", "text/plain")], 61 | } 62 | } 63 | cherrypy.config.update(globalConf) 64 | cherrypy.tree.mount(WebServer(handlers=self.handlers), "/", config=apiConf) 65 | cherrypy.engine.start() 66 | self.logger.debug( 67 | "Started web server on {}{}{}...".format(self.host, ":", self.port) 68 | ) 69 | 70 | 71 | class WebServer(object): 72 | def __init__(self, *args, **kwargs): 73 | self.logger = logging.getLogger("webhooks") 74 | self.handlers = {} 75 | for m, h in kwargs.get("handlers", {}).items(): 76 | if callable(h): 77 | self.logger.debug( 78 | "Registered callable object {} for the {} method.".format(h, m) 79 | ) 80 | self.handlers.update({m: h}) 81 | else: 82 | self.logger.error( 83 | "Object {} is not callable; the {} method will not be supported.".format( 84 | h, m 85 | ) 86 | ) 87 | 88 | @cherrypy.expose() 89 | def default(self, *args, **kwargs): 90 | self.logger.debug( 91 | "Received {} request. args: {}, kwargs: {}".format( 92 | cherrypy.request.method, args, kwargs 93 | ) 94 | ) 95 | 96 | if cherrypy.request.method not in self.handlers.keys(): 97 | # Unsupported method 98 | self.logger.debug("Ignoring request due to unsupported method.") 99 | cherrypy.response.status = 405 # Method Not Allowed 100 | return 101 | else: 102 | if self.handlers.get(cherrypy.request.method): 103 | self.logger.debug( 104 | "Calling {} to process the request...".format( 105 | self.handlers[cherrypy.request.method] 106 | ) 107 | ) 108 | handler_response = self.handlers[cherrypy.request.method]( 109 | cherrypy.request, *args, **kwargs 110 | ) 111 | else: 112 | self.logger.error( 113 | "No handler available for method {}. Ignoring request.".format( 114 | cherrypy.request.method 115 | ) 116 | ) 117 | cherrypy.response.status = 500 # Internal Server Error 118 | return 119 | 120 | return handler_response or "OK" 121 | --------------------------------------------------------------------------------