├── .gitignore ├── LICENSE ├── README.md ├── sandesh ├── __init__.py └── send.py ├── setup.cfg └── setup.py /.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 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-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 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Abhishek Thakur 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | +-+-+-+-+-+-+-+ 3 | |s|a|n|d|e|s|h| 4 | +-+-+-+-+-+-+-+ 5 | 6 | sandesh (संदेश) in Hindi means message. 7 | This is a simple python library to send messages to Slack using webhook urls. 8 | 9 | ### Installing 10 | 11 | You can install the bleeding edge version of this library by doing: 12 | 13 | ``` 14 | git clone git@github.com:abhishekkrthakur/sandesh.git 15 | cd sandesh 16 | python setup.py install 17 | ``` 18 | 19 | Or from pip: 20 | 21 | ``` 22 | pip install sandesh 23 | ``` 24 | 25 | ### Usage 26 | 27 | Using sandesh is very easy. 28 | 29 | First of all you need a webhook. You can either keep this webhook as environment variable: `SANDESH_WEBHOOK` 30 | Or you can send it in the `send` function: `sandesh.send(msg, webhook="XXXXX")`. 31 | 32 | I like to keep it as environment variable so that I dont accidently push it to GitHub ;) 33 | 34 | You can send a message to the provided webhook by doing: 35 | 36 | ``` 37 | import sandesh 38 | 39 | loss = 0.15 40 | msg = f"Training loss was {loss}" 41 | sandesh.send(msg) 42 | ``` 43 | 44 | sandesh also supports dictionaries, OrderedDict and defaultdict. An example for OrderedDict is provided below: 45 | 46 | ``` 47 | import collections 48 | import sandesh 49 | 50 | log = collections.OrderedDict([ 51 | ('training_epoch', 5), 52 | ('loss', 0.08) 53 | ]) 54 | sandesh.send(log) 55 | ``` 56 | 57 | If you want to go fancy, take a look at custom messages for slack. You can create your own custom message and send using: 58 | 59 | ``` 60 | import sandesh 61 | 62 | # data = Fancy slack json 63 | sandesh.send(data, use_raw=True) 64 | ``` 65 | 66 | 67 | This is a simple app that I use to send me notifications of my training processes from home workstation or AWS/GCP machines. 68 | -------------------------------------------------------------------------------- /sandesh/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.3.2" 2 | 3 | from .send import send 4 | -------------------------------------------------------------------------------- /sandesh/send.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple slack message sender 3 | """ 4 | import collections 5 | import json 6 | import os 7 | import requests 8 | from loguru import logger 9 | 10 | 11 | def http_post(url: str, timeout: int = 5, payload=None) -> requests.Response: 12 | try: 13 | response = requests.post(url=url, data=payload, timeout=timeout) 14 | except requests.exceptions.ConnectionError: 15 | logger.error("❌ Failed to reach slack webhook. Check your internet connection") 16 | except requests.exceptions.HTTPError: 17 | logger.error("❌ Slack webhook returned an error") 18 | except requests.exceptions.Timeout: 19 | logger.error("❌ Slack webhook timed out") 20 | except requests.exceptions.RequestException: 21 | logger.error("❌ Slack webhook returned an error") 22 | except Exception as e: 23 | logger.error(f"❌ Slack webhook error: {e}") 24 | if response.status_code != 200: 25 | logger.error(f"❌ Slack webhook returned status code: {response.status_code}") 26 | else: 27 | logger.info("✅ Message sent to slack") 28 | 29 | 30 | def send(msg, timeout=5, use_raw=False, webhook=None): 31 | """ 32 | A function to send messages on slack 33 | :param msg: string, list of strings, dictionary (or defaultdict/OrderedDict) 34 | :param use_raw: if True, msg (dict) is dumped as json and sent to slack. Use for advanced messages 35 | :param webhook: Slack webhook URL. Either this or SANDESH_WEBHOOK environment variable should be present 36 | """ 37 | if webhook is None: 38 | webhook = os.environ.get("SANDESH_WEBHOOK") 39 | 40 | if webhook is None: 41 | logger.error("Sandesh: No webhooks found") 42 | return 43 | 44 | data = dict() 45 | 46 | if isinstance(msg, str): 47 | data = { 48 | "blocks": [ 49 | { 50 | "type": "section", 51 | "text": { 52 | "type": "mrkdwn", 53 | "text": msg, 54 | }, 55 | } 56 | ] 57 | } 58 | http_post(webhook, payload=json.dumps(data), timeout=timeout) 59 | 60 | elif isinstance(msg, list): 61 | data["text"] = "\n".join(msg) 62 | http_post(webhook, payload=json.dumps(data), timeout=timeout) 63 | 64 | elif isinstance(msg, (dict, collections.defaultdict, collections.OrderedDict)): 65 | values = [] 66 | for k, v in msg.items(): 67 | values.append(str(k) + ": " + str(v)) 68 | data["text"] = "\n".join(values) 69 | http_post(webhook, payload=json.dumps(data), timeout=timeout) 70 | 71 | elif isinstance(msg, dict) and use_raw is True: 72 | http_post(webhook, payload=json.dumps(msg), timeout=timeout) 73 | 74 | else: 75 | logger.error("Sandesh: Type for variable `msg`, is currently not supported") 76 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, Extension 2 | from setuptools import find_packages 3 | 4 | import sandesh 5 | 6 | with open("README.md", encoding="utf-8") as f: 7 | long_description = f.read() 8 | 9 | INSTALL_REQUIRES = [ 10 | "loguru", 11 | ] 12 | 13 | if __name__ == "__main__": 14 | setup( 15 | name="sandesh", 16 | version=sandesh.__version__, 17 | description="sandesh - a simple app to send messages on slack", 18 | long_description=long_description, 19 | long_description_content_type="text/markdown", 20 | author="Abhishek Thakur", 21 | url="https://github.com/abhishekkrthakur/sandesh", 22 | license="MIT License", 23 | packages=find_packages(), 24 | include_package_data=True, 25 | platforms=["linux", "unix"], 26 | python_requires=">=3.7", 27 | install_requires=INSTALL_REQUIRES, 28 | ) 29 | --------------------------------------------------------------------------------