thermoprint-homework/jobs/joke.py
2025-12-23 16:32:16 +01:00

47 lines
1.6 KiB
Python

import textwrap
from jobs.joke_sources import JednorozecJokeSource, BestPageJokeSource
class JokeJob:
def __init__(self):
self.sources = [
JednorozecJokeSource(),
BestPageJokeSource()
]
self.selected_source = self.sources[0]
def get_name(self):
return "Random Joke"
def configure(self):
print("\nSelect Joke Source:")
for i, source in enumerate(self.sources):
print(f" [{i + 1}] {source.get_name()}")
choice = input(f"Choice [{self.sources.index(self.selected_source) + 1}]: ").strip()
if choice:
try:
idx = int(choice) - 1
if 0 <= idx < len(self.sources):
self.selected_source = self.sources[idx]
except ValueError:
pass
def run(self, printer):
try:
joke = self.selected_source.fetch_joke()
if joke:
# Wrap text to avoid word splitting (assuming ~42 chars for 80mm paper)
wrapped_joke = "\n".join([textwrap.fill(line, width=42) for line in joke.splitlines()])
printer.text(f"Joke from {self.selected_source.get_name()}:\n")
printer.text("--------------------------------\n\n")
printer.text(wrapped_joke)
printer.text("\n\n")
else:
printer.text("Sorry, could not extract any jokes from the website.\n")
except Exception as e:
printer.text(f"Error fetching joke: {e}\n")
printer.cut()