reworked validation

This commit is contained in:
Simone Robutti 2021-05-02 10:37:46 +02:00
parent a6a14d2689
commit fb00516d6c
2 changed files with 32 additions and 42 deletions

View File

@ -4,63 +4,51 @@ from .abstract import AbstractPublisher
class TelegramPublisher(AbstractPublisher):
def post(self) -> bool:
chat_id = self.credentials['chat_id']
text = self.event['text']
token = self.credentials['token']
post_params_kwargs = self.event.get('post_params_kwargs')
chat_id = self.credentials["chat_id"]
text = self.event["text"]
token = self.credentials["token"]
post_params_kwargs = self.event.get("post_params_kwargs")
res = requests.post(
url=f'https://api.telegram.org/bot{token}/sendMessage',
params=dict(chat_id=chat_id, text=text, **post_params_kwargs)
url=f"https://api.telegram.org/bot{token}/sendMessage",
params=dict(chat_id=chat_id, text=text, **post_params_kwargs),
)
data = self.__validate_response(res)
if data.get('__error'):
self.log_error(data['__error'])
return False
return self._validate_response(res)
return True
def _log_error_and_raise(self, message):
self.log_error(message)
raise ValueError(message)
def validate_credentials(self) -> bool:
chat_id = self.credentials.get('chat_id')
token = self.credentials.get('token')
username = self.credentials.get('username')
if any(a is None for a in (chat_id, token, username)):
self.log_error("Required info is missing")
return False
chat_id = self.credentials.get("chat_id")
token = self.credentials.get("token")
username = self.credentials.get("username")
if all([chat_id, token, username]):
# TODO: add composable errors to highlight which credentials are missing
self._log_error_and_raise("Some credentials are missing")
res = requests.get(f'https://api.telegram.org/bot{token}/getMe')
data = self.__validate_response(res)
if data.get('__error'):
self.log_error(data['__error'])
return False
res = requests.get(f"https://api.telegram.org/bot{token}/getMe")
data = self._validate_response(res)
if not username == data.get('result', {}).get('username'):
self.log_error("Found a different bot than the expected one!")
return False
return True
if not username == data.get("result", {}).get("username"):
self._log_error_and_raise("Found a different bot than the expected one")
return data
def validate_event(self) -> bool:
text = self.event.get('text')
text = self.event.get("text")
if not (text and text.strip()):
self.log_error(f"No text was found!")
return False
return True
self._log_error_and_raise("No text was found. Invalid event")
@staticmethod
def __validate_response(res):
try:
def _validate_response(self, res):
res.raise_for_status()
except requests.exceptions.HTTPError as e:
return {'__error': str(e)}
try:
data = res.json()
except ValueError:
return {'__error': "Server returned invalid json data"}
except ValueError as e:
self.log_error("Server returned invalid json data")
raise ValueError from e
if not data.get('ok'):
data['__error'] = f"Invalid request (response: {data})"
if not data.get("ok"):
raise ValueError(f"Invalid request (response: {data})")
return data

2
setup.cfg Normal file
View File

@ -0,0 +1,2 @@
[flake8]
max-line-length=120