#!/usr/bin/env python """ Message sender component. """ import logging import random import string import json from communicator import Communicator __author__ = "@kovacsbence" __copyright__ = "Copyright 2020, GoldenPogácsa Team" __module_name__ = "messagesender" __version__text__ = "1" logging.basicConfig(level=logging.INFO) LOGGER = logging.getLogger(__name__) class MessageSender: """ Component responsible for sending the messages. Requires an instance of :class:`communicator.Communicator`. """ def __init__(self, communicator: Communicator, uuid: str): """**Constructor:** Initializes the object. :param communicator: an instance of :class:`communicator.Communicator`. """ self.communicator = communicator self.uuid = uuid def randomstring(self, stringlength: int) -> str: """Generate a random string of fixed length :param stringlength: the length of the string :return: the generated string """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringlength)) def sendmessage(self, message: str = "") -> None: """Sends the given message. If the message is omitted (empty), then a random message will be generated with length 23 (with :func:`messagesender.MessageSender.randomstring`. Calls :func:`communicator.Communicator.sendmessage` to send the message. :param message: the message of type string that will be sent. :return: None """ if not message: data = self.randomstring(32) else: data = message self.communicator.sendmessage(json.dumps({"message": data, "uuid": self.uuid}))