Skip to content

Commit

Permalink
Docstrings and typing.
Browse files Browse the repository at this point in the history
  • Loading branch information
iwatkot committed Jan 23, 2024
1 parent 548037f commit f66af70
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 2 deletions.
79 changes: 78 additions & 1 deletion src/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,21 @@


class Session:
"""Represents a session of map generation. Stores all the necessary data.
Args:
telegram_id (int): Telegram ID of the user.
coordinates (tuple[float, float]): Coordinates of the center of the map.
Attributes:
telegram_id (int): Telegram ID of the user.
timestamp (int): Timestamp of the session creation.
name (str): Name of the session.
coordinates (tuple[float, float]): Coordinates of the center of the map.
distance (int): Distance from the center of the map to the edge.
dem_settings (generate.DemSettings): DEM settings.
"""

def __init__(self, telegram_id: int, coordinates: tuple[float, float]):
self.telegram_id = telegram_id
self.timestamp = int(datetime.now().timestamp())
Expand All @@ -36,7 +51,12 @@ def __init__(self, telegram_id: int, coordinates: tuple[float, float]):
self.distance = None
self.dem_settings = None

def run(self):
def run(self) -> tuple[str, str]:
"""Runs the session and returns paths to the preview and the archive.
Returns:
tuple[str, str]: Paths to the preview and the archive.
"""
gm = generate.Map(
working_directory, self.coordinates, self.distance, self.dem_settings, logger, self.name
)
Expand All @@ -47,6 +67,11 @@ def run(self):

@dp.message_handler(commands=["start"])
async def start(message: types.Message) -> None:
"""Handles the /start command.
Args:
message (types.Message): Message, which triggered the handler.
"""
await log_event(message)

await bot.send_message(
Expand All @@ -58,6 +83,11 @@ async def start(message: types.Message) -> None:

@dp.message_handler(Text(equals=Buttons.GITHUB.value))
async def button_github(message: types.Message) -> None:
"""Handles the GitHub button.
Args:
message (types.Message): Message, which triggered the handler.
"""
await log_event(message)

await bot.send_message(
Expand All @@ -70,6 +100,11 @@ async def button_github(message: types.Message) -> None:

@dp.message_handler(Text(equals=Buttons.COFFEE.value))
async def button_coffee(message: types.Message) -> None:
"""Handles the Buy me a coffee button.
Args:
message (types.Message): Message, which triggered the handler.
"""
await log_event(message)

await bot.send_message(
Expand All @@ -82,6 +117,11 @@ async def button_coffee(message: types.Message) -> None:

@dp.message_handler(Text(equals=Buttons.GENERATE.value))
async def button_generate(message: types.Message) -> None:
"""Handles the Generate button, registers the coordinates handler.
Args:
message (types.Message): Message, which triggered the handler.
"""
await log_event(message)

dp.register_message_handler(coordinates)
Expand All @@ -97,6 +137,11 @@ async def button_generate(message: types.Message) -> None:

@dp.message_handler(Text(equals=Buttons.CANCEL.value))
async def cancel_button(message: types.Message) -> None:
"""Handles the Cancel button, returns to the main menu.
Args:
message (types.Message): Message, which triggered the handler.
"""
await log_event(message)

await bot.send_message(
Expand All @@ -107,6 +152,12 @@ async def cancel_button(message: types.Message) -> None:


async def coordinates(message: types.Message) -> None:
"""Handles the coordinates input, can be accessed only as a next step after the Generate button.
Checks if the coordinates are correct and creates inline buttons for map sizes.
Args:
message (types.Message): Message, which triggered the handler.
"""
await log_event(message)

if message.text == Buttons.CANCEL.value:
Expand Down Expand Up @@ -151,6 +202,11 @@ async def coordinates(message: types.Message) -> None:

@dp.callback_query_handler(text_contains="map")
async def map_size_callback(callback_query: types.CallbackQuery) -> None:
"""Handles the callback from the map size inline buttons, creates inline buttons for max heights.
Args:
callback_query (types.CallbackQuery): Callback, which triggered the handler.
"""
await log_event(callback_query)

map_size = int(callback_query.data.rsplit("_", 1)[-1])
Expand All @@ -173,6 +229,12 @@ async def map_size_callback(callback_query: types.CallbackQuery) -> None:

@dp.callback_query_handler(text_contains="max_height_")
async def max_height_callback(callback_query: types.CallbackQuery) -> None:
"""Handles the callback from the max height inline buttons, starts the generation process.
Sends the preview and the archive.
Args:
callback_query (types.CallbackQuery): Callback, which triggered the handler.
"""
await log_event(callback_query)

max_height = int(callback_query.data.rsplit("_", 1)[-1])
Expand Down Expand Up @@ -206,6 +268,16 @@ async def max_height_callback(callback_query: types.CallbackQuery) -> None:
async def keyboard(
buttons: list[str] | dict[str, str]
) -> ReplyKeyboardMarkup | InlineKeyboardMarkup:
"""Creates a keyboard with buttons depending on the input.
If the input is a list, creates a ReplyKeyboardMarkup.
If the input is a dict, creates an InlineKeyboardMarkup, where keys are callback_data and values are text.
Args:
buttons (list[str] | dict[str, str]): List or dict of buttons.
Returns:
ReplyKeyboardMarkup | InlineKeyboardMarkup: Keyboard with buttons.
"""
if isinstance(buttons, list):
keyboard = ReplyKeyboardMarkup(
resize_keyboard=True,
Expand All @@ -224,6 +296,11 @@ async def keyboard(


async def log_event(data: types.Message | types.CallbackQuery) -> None:
"""Logs the event.
Args:
data (types.Message | types.CallbackQuery): Data, which triggered the handler.
"""
try:
logger.debug(
f"Message from {data.from_user.username} with telegram ID {data.from_user.id}: {data.text}"
Expand Down
4 changes: 4 additions & 0 deletions src/bot_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@


class Messages(Enum):
"""Messages, which are used in the bot."""

START = (
"Hello, I'm a bot that can generate map templates for Farming Simulator.\n\n"
"To get started, use the menu below."
Expand Down Expand Up @@ -43,6 +45,8 @@ class Messages(Enum):


class Buttons(Enum):
"""Buttons, which are used in the bot menu."""

GENERATE = "🗺️ Generate new map"
GITHUB = "🐙 Open on GitHub"
COFFEE = "☕ Buy me a coffee"
Expand Down
12 changes: 11 additions & 1 deletion src/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,11 @@ def _normalize_dem(self, data: np.ndarray) -> np.ndarray:
return normalized_data

def pack(self) -> str:
"""Packs map directory to zip archive.
Returns:
str: Path to the archive.
"""
archives_dir = os.path.join(self.working_directory, "archives")
os.makedirs(archives_dir, exist_ok=True)
archive_name = self.name if self.name else "map"
Expand All @@ -577,7 +582,12 @@ def pack(self) -> str:
self.logger.log(f"Map packed to {archive_path}.")
return archive_path

def preview(self) -> list[str]:
def preview(self) -> str:
"""Merges layers into one image and saves it to previews directory.
Returns:
str: Path to the preview.
"""
preview_size = (2048, 2048)
images = [
cv2.resize(cv2.imread(layer.path, cv2.IMREAD_UNCHANGED), preview_size)
Expand Down

0 comments on commit f66af70

Please sign in to comment.