Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Message class to the backend #10

Merged
merged 6 commits into from
Oct 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import sys

pybliotecario_name = "pybliotecario"
print(sys.argv)
if "--with_name" in sys.argv:
import socket

Expand All @@ -15,8 +14,6 @@
# Remove it from the list of argument, nobody should know
sys.argv.remove("--with_name")

print(sys.argv)

# Readup the readme
README = (pathlib.Path(__file__).parent / "readme.md").read_text()
setup(
Expand All @@ -33,13 +30,13 @@
packages=find_packages("src"),
install_requires=[
"numpy",
"requests",
"regex",
"arxiv",
"pyowm",
"psutil",
"wikipedia",
],
extra_requires={"facebook": ["flask"]},
entry_points={
"console_scripts": [
"{0} = pybliotecario.pybliotecario:main".format(pybliotecario_name),
Expand Down
116 changes: 0 additions & 116 deletions src/pybliotecario/Message.py

This file was deleted.

2 changes: 0 additions & 2 deletions src/pybliotecario/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
__version__ = "2.0.0"

from pybliotecario.Message import Message
6 changes: 4 additions & 2 deletions src/pybliotecario/argument_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def configure_telegram(main_folder):
teleAPI = TelegramUtil(token, timeout=20)
while True:
all_updates = teleAPI.get_updates(not_empty=True)
from pybliotecario.Message import Message
from pybliotecario.backend.telegram_util import TelegramMessage

update = Message(all_updates[0])
print("Message received: {0}".format(update.text))
Expand Down Expand Up @@ -163,7 +163,9 @@ def parse_args(args):
""" Wrapper for ArgumentParser """
parser = ArgumentParser()
parser.add_argument(
"--init", help="Wizard to configure the pybliotecario for the first time", action=InitAction
"--init",
help="Wizard to configure the pybliotecario for the first time",
action=InitAction,
)
parser.add_argument("--config_file", help="Define a custom configuration file")
parser.add_argument("--backend", help="Choose backend", type=str, default="Telegram")
Expand Down
15 changes: 5 additions & 10 deletions src/pybliotecario/backend/backend_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@
without communication with any service
"""

import copy
import pathlib
import numpy as np
from datetime import datetime
import numpy as np

from pybliotecario.Message import Message
from pybliotecario.backend.telegram_util import TelegramMessage

TESTID = 1234 # chat id for the test backend
_TESTUSER = "hiro"


class TestMessage(Message):
class TestMessage(TelegramMessage):
""" Copy of the TelegramMessage class """

_type = "Test"


Expand Down Expand Up @@ -122,9 +123,3 @@ def is_msg_in_file(self, msg):
This is something that is only useful for the TestUtil backend"""
read_text = self.comm_file.read_text()
return msg in read_text


if __name__ == "__main__":
cls = TestUtil("/tmp/test.txt")
res = cls._get_updates()
msgs = [TestMessage(i) for i in res]
153 changes: 153 additions & 0 deletions src/pybliotecario/backend/basic_backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"""
Base/abstract backend classes:

- Message
- Backend

Each backend should implement its own message type and inherit from backend
"""

from abc import ABC, abstractmethod, abstractproperty
import logging
import json

logger = logging.getLogger(__name__)


class Message(ABC):
"""
Base message class

Any implementation of the message should either save a dictionary
``_message_dict`` with the following attributes (through _parse_update)
or implement its own way of getting the different values
"""

_type = "Abstract"
_original = None

_message_dict = {
"chat_id": None,
"username": None,
"command": None,
"file_id": None,
"text": None,
"ignore": False,
}

def __init__(self, update):
self._original = update
self._parse_update(update)
# After the information is parsed, log the message!
logger.info("New message: %s", self)

def __str__(self):
return json.dumps(self._message_dict)

@abstractmethod
def _parse_update(self, update):
""" Parse the update and fill in _message_dict """
return None

@property
def chat_id(self):
""" Returns the chat id """
return self._message_dict["chat_id"]

@property
def username(self):
""" Returns the username """
return self._message_dict["username"]

@property
def text(self):
""" Returns the content of the message """
return self._message_dict.get("text")

@property
def is_command(self):
""" Returns true if the message is a command """
return self._message_dict.get("command") is not None

@property
def command(self):
""" Returns the command contained in the message """
return self._message_dict.get("command")

@property
def is_file(self):
""" Returns true if the message is a file """
return self._message_dict.get("file_id") is not None

@property
def file_id(self):
""" Returns the id of the file """
return self._message_dict.get("file_id")

@property
def has_arguments(self):
""" Returns true if the message is a command with arguments """
return self.is_command and self.text is not None

@property
def ignore(self):
""" Returns true if the message is to be ignored """
return self._message_dict.get("ignore", False)

@ignore.setter
def ignore(self, val):
self._message_dict["ignore"] = val


class Backend(ABC):
"""
Main backend class for inheritting.

It provides a number of base functions and wrappers

The minimum set of methods and properties the backend must define are:

_message_class: a reference to the Message class of the backend
_get_updates: a method that should return a list of updates to act upon
send_message: a method to communicate messages

Others:
- send_image
- send_file
- download_file

"""

@abstractmethod
def _get_updates(self, not_empty=False):
""" Retrieve updates """

@abstractmethod
def send_message(self, text, chat):
""" Sends a message to the chat """

@abstractproperty
def _message_class(self):
pass

def act_on_updates(self, action_function, not_empty=False):
"""
Receive the input using _get_updates, parse it with
the telegram message class and act in consequence
"""
all_updates = self._get_updates(not_empty=not_empty)
for update in all_updates:
msg = self._message_class(update)
action_function(msg)

def send_image(self, img_path, chat):
""" Sends an image """
logger.error("This backend does not implement sending files")

def send_file(self, filepath, chat):
""" Sends a file """
logger.error("This backend does not implement sending files")

def download_file(self, file_id, file_name_raw):
""" Downloads a file """
logger.error("This backend does not support downloading files")
Loading