stable/freqtrade/rpc/webhook.py

124 lines
4.6 KiB
Python
Raw Normal View History

2018-07-05 19:32:53 +00:00
"""
This module manages webhook communication
"""
import logging
import time
2022-10-07 18:52:14 +00:00
from typing import Any, Dict, Optional
2018-07-05 19:32:53 +00:00
2020-09-28 17:39:41 +00:00
from requests import RequestException, post
2018-07-05 19:32:53 +00:00
2022-09-18 11:31:52 +00:00
from freqtrade.constants import Config
2021-06-09 17:51:44 +00:00
from freqtrade.enums import RPCMessageType
from freqtrade.rpc import RPC, RPCHandler
2018-07-05 19:32:53 +00:00
logger = logging.getLogger(__name__)
logger.debug('Included module rpc.webhook ...')
class Webhook(RPCHandler):
2018-07-05 19:32:53 +00:00
""" This class handles all webhook communication """
2022-09-18 11:31:52 +00:00
def __init__(self, rpc: RPC, config: Config) -> None:
2018-07-05 19:32:53 +00:00
"""
Init the Webhook class, and init the super class RPCHandler
:param rpc: instance of RPC Helper class
:param config: Configuration object
2018-07-05 19:32:53 +00:00
:return: None
"""
super().__init__(rpc, config)
2018-07-05 19:32:53 +00:00
2018-07-14 11:29:34 +00:00
self._url = self._config['webhook']['url']
2021-02-26 14:46:23 +00:00
self._format = self._config['webhook'].get('format', 'form')
self._retries = self._config['webhook'].get('retries', 0)
self._retry_delay = self._config['webhook'].get('retry_delay', 0.1)
2018-07-05 19:32:53 +00:00
def cleanup(self) -> None:
"""
Cleanup pending module resources.
This will do nothing for webhooks, they will simply not be called anymore
"""
pass
2022-10-07 18:52:14 +00:00
def _get_value_dict(self, msg: Dict[str, Any]) -> Optional[Dict[str, Any]]:
whconfig = self._config['webhook']
# Deprecated 2022.10 - only keep generic method.
if msg['type'] in [RPCMessageType.ENTRY]:
valuedict = whconfig.get('webhookentry')
elif msg['type'] in [RPCMessageType.ENTRY_CANCEL]:
valuedict = whconfig.get('webhookentrycancel')
elif msg['type'] in [RPCMessageType.ENTRY_FILL]:
valuedict = whconfig.get('webhookentryfill')
elif msg['type'] == RPCMessageType.EXIT:
valuedict = whconfig.get('webhookexit')
elif msg['type'] == RPCMessageType.EXIT_FILL:
valuedict = whconfig.get('webhookexitfill')
elif msg['type'] == RPCMessageType.EXIT_CANCEL:
valuedict = whconfig.get('webhookexitcancel')
elif msg['type'] in (RPCMessageType.STATUS,
RPCMessageType.STARTUP,
RPCMessageType.EXCEPTION,
2022-10-07 18:52:14 +00:00
RPCMessageType.WARNING):
valuedict = whconfig.get('webhookstatus')
elif msg['type'].value in whconfig:
# Allow all types ...
valuedict = whconfig.get(msg['type'].value)
elif msg['type'] in (
RPCMessageType.PROTECTION_TRIGGER,
RPCMessageType.PROTECTION_TRIGGER_GLOBAL,
RPCMessageType.WHITELIST,
RPCMessageType.ANALYZED_DF,
RPCMessageType.NEW_CANDLE,
2022-10-07 18:52:14 +00:00
RPCMessageType.STRATEGY_MSG):
# Don't fail for non-implemented types
return None
return valuedict
2018-07-05 19:32:53 +00:00
def send_msg(self, msg: Dict[str, Any]) -> None:
""" Send a message to telegram channel """
try:
2022-10-07 18:52:14 +00:00
valuedict = self._get_value_dict(msg)
2022-10-07 18:44:47 +00:00
2018-07-05 19:32:53 +00:00
if not valuedict:
2020-09-19 18:04:12 +00:00
logger.info("Message type '%s' not configured for webhooks", msg['type'])
2018-07-05 19:32:53 +00:00
return
2018-07-12 19:54:31 +00:00
payload = {key: value.format(**msg) for (key, value) in valuedict.items()}
2018-07-05 19:32:53 +00:00
self._send_msg(payload)
except KeyError as exc:
logger.exception("Problem calling Webhook. Please check your webhook configuration. "
"Exception: %s", exc)
def _send_msg(self, payload: dict) -> None:
2018-07-14 11:29:34 +00:00
"""do the actual call to the webhook"""
2018-07-05 19:32:53 +00:00
success = False
attempts = 0
while not success and attempts <= self._retries:
if attempts:
2021-11-29 18:54:54 +00:00
if self._retry_delay:
time.sleep(self._retry_delay)
logger.info("Retrying webhook...")
attempts += 1
try:
if self._format == 'form':
response = post(self._url, data=payload)
elif self._format == 'json':
response = post(self._url, json=payload)
elif self._format == 'raw':
2021-11-29 18:54:54 +00:00
response = post(self._url, data=payload['data'],
headers={'Content-Type': 'text/plain'})
else:
2023-03-19 16:50:08 +00:00
raise NotImplementedError(f'Unknown format: {self._format}')
2021-11-29 18:54:54 +00:00
2021-11-28 23:30:41 +00:00
# Throw a RequestException if the post was not successful
response.raise_for_status()
success = True
except RequestException as exc:
logger.warning("Could not call webhook url. Exception: %s", exc)