This repository has been archived on 2020-09-24. You can view files and clone it, but cannot push or open issues or pull requests.
producer/messagesender.py

60 lines
1.7 KiB
Python

#!/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}))