mango-explorer/Notification.ipynb

335 lines
9.7 KiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"id": "experimental-roman",
"metadata": {},
"source": [
"# ⚠ Warning\n",
"\n",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
"\n",
"[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gl/OpinionatedGeek%2Fmango-explorer/HEAD?filepath=Notification.ipynb) _🏃 To run this notebook press the ⏩ icon in the toolbar above._\n",
"\n",
"[🥭 Mango Markets](https://mango.markets/) support is available at: [Docs](https://docs.mango.markets/) | [Discord](https://discord.gg/67jySBhxrg) | [Twitter](https://twitter.com/mangomarkets) | [Github](https://github.com/blockworks-foundation) | [Email](mailto:hello@blockworks.foundation)"
]
},
{
"cell_type": "markdown",
"id": "serious-brave",
"metadata": {},
"source": [
"# 🥭 Notification\n",
"\n",
"This notebook contains code to send arbitrary notifications.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "altered-locking",
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [],
"source": [
"import abc\n",
"import logging\n",
"import requests\n",
"import typing\n"
]
},
{
"cell_type": "markdown",
"id": "artistic-supplier",
"metadata": {},
"source": [
"# NotificationTarget class\n",
"\n",
"This base class is the root of the different notification mechanisms.\n",
"\n",
"Derived classes should override `send_notification()` to implement their own sending logic.\n",
"\n",
"Derived classes should not override `send()` since that is the interface outside classes call and it's used to ensure `NotificationTarget`s don't throw an exception when sending."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "industrial-improvement",
"metadata": {},
"outputs": [],
"source": [
"class NotificationTarget(metaclass=abc.ABCMeta):\n",
" def __init__(self):\n",
" self.logger: logging.Logger = logging.getLogger(self.__class__.__name__)\n",
"\n",
" def send(self, item: typing.Any) -> None:\n",
" try:\n",
" self.send_notification(item)\n",
" except Exception as exception:\n",
" self.logger.error(f\"Error sending {item} - {self} - {exception}\")\n",
"\n",
" @abc.abstractmethod\n",
" def send_notification(self, item: typing.Any) -> None:\n",
" raise NotImplementedError(\"NotificationTarget.send() is not implemented on the base type.\")\n",
"\n",
" def __repr__(self) -> str:\n",
" return f\"{self}\"\n"
]
},
{
"cell_type": "markdown",
"id": "adjustable-software",
"metadata": {},
"source": [
"# TelegramNotificationTarget class\n",
"\n",
"The `TelegramNotificationTarget` sends messages to Telegram.\n",
"\n",
"The format for the telegram notification is:\n",
"1. The word 'telegram'\n",
"2. A colon ':'\n",
"3. The chat ID\n",
"4. An '@' symbol\n",
"5. The bot token\n",
"\n",
"For example:\n",
"```\n",
"telegram:<CHAT-ID>@<BOT-TOKEN>\n",
"```\n",
"\n",
"The [Telegram instructions to create a bot](https://core.telegram.org/bots#creating-a-new-bot) show you how to create the bot token."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "legal-vitamin",
"metadata": {},
"outputs": [],
"source": [
"class TelegramNotificationTarget(NotificationTarget):\n",
" def __init__(self, address):\n",
" super().__init__()\n",
" chat_id, bot_id = address.split(\"@\", 1)\n",
" self.chat_id = chat_id\n",
" self.bot_id = bot_id\n",
"\n",
" def send_notification(self, item: typing.Any):\n",
" payload = {\"disable_notification\": True, \"chat_id\": self.chat_id, \"text\": str(item)}\n",
" url = f\"https://api.telegram.org/bot{self.bot_id}/sendMessage\"\n",
" headers = {\"Content-Type\": \"application/json\"}\n",
" requests.post(url, json=payload, headers=headers)\n",
"\n",
" def __str__(self) -> str:\n",
" return f\"Telegram chat ID: {self.chat_id}\"\n"
]
},
{
"cell_type": "markdown",
"id": "systematic-matrix",
"metadata": {},
"source": [
"# DiscordNotificationTarget class\n",
"\n",
"The `DiscordNotificationTarget` sends messages to Discord.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "resistant-thanks",
"metadata": {},
"outputs": [],
"source": [
"class DiscordNotificationTarget(NotificationTarget):\n",
" def __init__(self, address):\n",
" super().__init__()\n",
" self.address = address\n",
"\n",
" def send_notification(self, item: typing.Any):\n",
" payload = {\n",
" \"content\": str(item)\n",
" }\n",
" url = self.address\n",
" headers = {\"Content-Type\": \"application/json\"}\n",
" requests.post(url, json=payload, headers=headers)\n",
"\n",
" def __str__(self) -> str:\n",
" return \"Discord webhook\"\n"
]
},
{
"cell_type": "markdown",
"id": "arabic-madison",
"metadata": {},
"source": [
"# parse_subscription_target() function\n",
"\n",
"`parse_subscription_target()` takes a parameter as a string and returns a notification target.\n",
"\n",
"This is most likely used when parsing command-line arguments - this function can be used in the `type` parameter of an `add_argument()` call."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fatty-airfare",
"metadata": {},
"outputs": [],
"source": [
"def parse_subscription_target(target):\n",
" protocol, address = target.split(\":\", 1)\n",
"\n",
" if protocol == \"telegram\":\n",
" return TelegramNotificationTarget(address)\n",
" elif protocol == \"discord\":\n",
" return DiscordNotificationTarget(address)\n",
" else:\n",
" raise Exception(f\"Unknown protocol: {protocol}\")\n"
]
},
{
"cell_type": "markdown",
"id": "worst-kelly",
"metadata": {},
"source": [
"## NotificationHandler class\n",
"\n",
"A bridge between the worlds of notifications and logging. This allows any `NotificationTarget` to be plugged in to the `logging` subsystem to receive log messages and notify however it chooses."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "normal-disclaimer",
"metadata": {},
"outputs": [],
"source": [
"class NotificationHandler(logging.StreamHandler):\n",
" def __init__(self, target: NotificationTarget):\n",
" logging.StreamHandler.__init__(self)\n",
" self.target = target\n",
"\n",
" def emit(self, record):\n",
" message = self.format(record)\n",
" self.target.send_notification(message)\n"
]
},
{
"cell_type": "markdown",
"id": "civil-cornell",
"metadata": {},
"source": [
"# ✅ Testing"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "severe-amsterdam",
"metadata": {},
"outputs": [],
"source": [
"def _notebook_tests():\n",
" test_target = parse_subscription_target(\"telegram:chat@bot\")\n",
"\n",
" assert(test_target.chat_id == \"chat\")\n",
" assert(test_target.bot_id == \"bot\")\n",
"\n",
"\n",
"_notebook_tests()\n",
"del _notebook_tests"
]
},
{
"cell_type": "markdown",
"id": "young-paragraph",
"metadata": {},
"source": [
"# 🏃 Running\n",
"\n",
"A few quick examples to show how to use these functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "naval-transportation",
"metadata": {},
"outputs": [],
"source": [
"if __name__ == \"__main__\":\n",
" test_target = parse_subscription_target(\"telegram:chat@bot\")\n",
" print(test_target)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": true
},
"varInspector": {
"cols": {
"lenName": 16,
"lenType": 16,
"lenVar": 40
},
"kernels_config": {
"python": {
"delete_cmd_postfix": "",
"delete_cmd_prefix": "del ",
"library": "var_list.py",
"varRefreshCmd": "print(var_dic_list())"
},
"r": {
"delete_cmd_postfix": ") ",
"delete_cmd_prefix": "rm(",
"library": "var_list.r",
"varRefreshCmd": "cat(var_dic_list()) "
}
},
"types_to_exclude": [
"module",
"function",
"builtin_function_or_method",
"instance",
"_Feature"
],
"window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 5
}