-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
346 lines (278 loc) · 11.6 KB
/
Copy pathapp.py
File metadata and controls
346 lines (278 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# app.py
# LaundryBot - Telegram bot to manage laundry bookings with a conversational interface
import logging
import asyncio
import json
import os
import sys
from datetime import datetime, timedelta
# ---------------- CONFIGURATION CHECK ----------------
try:
import config
except ModuleNotFoundError:
print("Error: config.py not found! Copy config.example.py to config.py and add your BOT_TOKEN.")
sys.exit(1)
# ---------------- TELEGRAM IMPORTS ----------------
from telegram import Update, ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove
from telegram.ext import (
ApplicationBuilder,
ContextTypes,
CommandHandler,
MessageHandler,
filters,
ConversationHandler
)
# ---------------- LOGGING ----------------
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# ---------------- CONVERSATION STATES ----------------
# Booking flow states
CHOOSE_TYPE, CHOOSE_MACHINE, DURATION = range(3)
# Empty/free flow state (separate namespace to avoid conflicts)
EMPTY_CHOOSE_MACHINE = 3
# ---------------- MACHINE DATA ----------------
washing_machines = ["A", "B", "C", "D", "E"]
dryers = ["1", "2", "3", "4"]
# Bookings dictionary.
# Structure: {machine_name: {"user": username, "end_time": iso_string, "minutes": int}}
bookings = {}
# ---------------- PERSISTENCE ----------------
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
BOOKINGS_FILE = os.path.join(DATA_DIR, "bookings.json")
def load_bookings():
"""Load bookings from JSON file, discarding expired ones."""
global bookings
os.makedirs(DATA_DIR, exist_ok=True)
if not os.path.exists(BOOKINGS_FILE):
bookings = {}
return
try:
with open(BOOKINGS_FILE, "r") as f:
raw = json.load(f)
now = datetime.utcnow()
# Filter out expired bookings
bookings = {
machine: data
for machine, data in raw.items()
if datetime.fromisoformat(data["end_time"]) > now
}
logger.info(f"Loaded {len(bookings)} active booking(s) from disk.")
except (json.JSONDecodeError, KeyError, ValueError):
logger.warning("Could not parse bookings.json, starting fresh.")
bookings = {}
def save_bookings():
"""Persist current bookings to JSON file."""
os.makedirs(DATA_DIR, exist_ok=True)
with open(BOOKINGS_FILE, "w") as f:
json.dump(bookings, f, indent=2)
# ---------------- HELPER FUNCTIONS ----------------
def available_machines(machine_type: str) -> list[str]:
"""Return machines of the given type that are not currently booked."""
pool = washing_machines if machine_type == "washing" else dryers
return [m for m in pool if m not in bookings]
def booked_machines(machine_type: str) -> list[str]:
"""Return machines of the given type that are currently booked."""
pool = washing_machines if machine_type == "washing" else dryers
return [m for m in pool if m in bookings]
def format_booking_list() -> str:
"""Return a human-readable summary of all active bookings."""
if not bookings:
return "Nessuna prenotazione attiva. ✅"
lines = ["📋 *Prenotazioni attive:*\n"]
for machine, data in bookings.items():
end_dt = datetime.fromisoformat(data["end_time"])
# Show remaining minutes
remaining = max(0, int((end_dt - datetime.utcnow()).total_seconds() / 60))
label = "🫧 Lavatrice" if machine in washing_machines else "🌀 Asciugatrice"
lines.append(
f"{label} *{machine}* — {data['user']} — ancora ~{remaining} min"
)
return "\n".join(lines)
# ---------------- COMMAND: /start (booking flow) ----------------
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Entry point: ask the user whether they want to book a washer or dryer."""
keyboard = [[KeyboardButton("🫧 Lavatrice"), KeyboardButton("🌀 Asciugatrice")]]
await update.message.reply_text(
"👋 Benvenuto su *LaundryBot*!\n\nCosa vuoi prenotare?",
parse_mode="Markdown",
reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True),
)
return CHOOSE_TYPE
async def choose_type(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle machine-type choice."""
text = update.message.text.strip()
if "lavatrice" in text.lower():
machine_type = "washing"
label = "lavatrice"
elif "asciugatrice" in text.lower():
machine_type = "dryer"
label = "asciugatrice"
else:
await update.message.reply_text("Per favore scegli *Lavatrice* o *Asciugatrice*.", parse_mode="Markdown")
return CHOOSE_TYPE
context.user_data["type"] = machine_type
machines = available_machines(machine_type)
if not machines:
await update.message.reply_text(
f"😕 Tutte le {label}e sono attualmente occupate.",
reply_markup=ReplyKeyboardRemove(),
)
return ConversationHandler.END
keyboard = [[KeyboardButton(m)] for m in machines]
await update.message.reply_text(
f"Quale {label} vuoi prenotare?",
reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True),
)
return CHOOSE_MACHINE
async def choose_machine(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle specific machine selection."""
machine = update.message.text.strip()
m_type = context.user_data.get("type", "washing")
valid = washing_machines if m_type == "washing" else dryers
if machine not in valid:
await update.message.reply_text("⚠️ Selezione non valida. Riprova.")
return CHOOSE_MACHINE
if machine in bookings:
await update.message.reply_text(
f"⚠️ La macchina *{machine}* è già prenotata. Scegline un'altra.",
parse_mode="Markdown",
)
return CHOOSE_MACHINE
context.user_data["machine"] = machine
await update.message.reply_text(
"⏱ Per quanti minuti la userai?",
reply_markup=ReplyKeyboardRemove(),
)
return DURATION
async def duration(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle booking duration and confirm."""
try:
minutes = int(update.message.text.strip())
if minutes <= 0:
raise ValueError
except ValueError:
await update.message.reply_text("⚠️ Inserisci un numero intero positivo di minuti.")
return DURATION
machine = context.user_data["machine"]
user = update.message.from_user.username or update.message.from_user.first_name
end_time = datetime.utcnow() + timedelta(minutes=minutes)
bookings[machine] = {
"user": user,
"end_time": end_time.isoformat(),
"minutes": minutes,
}
save_bookings()
await update.message.reply_text(
f"✅ *{machine}* prenotata da *{user}* per *{minutes}* minuti.\n"
f"Libera alle {(datetime.now() + timedelta(minutes=minutes)).strftime('%H:%M')} circa.",
parse_mode="Markdown",
reply_markup=ReplyKeyboardRemove(),
)
# Schedule automatic release
asyncio.create_task(release_machine(machine, minutes))
return ConversationHandler.END
async def release_machine(machine: str, minutes: int):
"""Release a machine automatically after its booking expires."""
await asyncio.sleep(minutes * 60)
if machine in bookings:
del bookings[machine]
save_bookings()
logger.info(f"Machine {machine} released automatically after {minutes} minutes.")
# ---------------- COMMAND: /view ----------------
async def view(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show all active bookings."""
await update.message.reply_text(
format_booking_list(),
parse_mode="Markdown",
reply_markup=ReplyKeyboardRemove(),
)
# ---------------- COMMAND: /cancel (inside conversation) ----------------
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Cancel the current operation."""
await update.message.reply_text(
"❌ Operazione annullata.",
reply_markup=ReplyKeyboardRemove(),
)
return ConversationHandler.END
# ---------------- COMMAND: /free — manually free a specific machine ----------------
async def free_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Ask which booked machine to free."""
all_booked = [m for m in bookings]
if not all_booked:
await update.message.reply_text(
"ℹ️ Non ci sono macchine prenotate al momento.",
reply_markup=ReplyKeyboardRemove(),
)
return ConversationHandler.END
keyboard = [[KeyboardButton(m)] for m in all_booked]
await update.message.reply_text(
"🗑 Quale macchina vuoi liberare?",
reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True),
)
return EMPTY_CHOOSE_MACHINE
async def free_choose_machine(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Free the chosen machine."""
machine = update.message.text.strip()
if machine not in bookings:
await update.message.reply_text(
f"⚠️ *{machine}* non risulta prenotata.",
parse_mode="Markdown",
reply_markup=ReplyKeyboardRemove(),
)
return ConversationHandler.END
booked_by = bookings[machine]["user"]
del bookings[machine]
save_bookings()
await update.message.reply_text(
f"✅ Macchina *{machine}* liberata (era prenotata da {booked_by}).",
parse_mode="Markdown",
reply_markup=ReplyKeyboardRemove(),
)
return ConversationHandler.END
# ---------------- COMMAND: /help ----------------
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Send a help message."""
text = (
"🤖 *LaundryBot — Comandi disponibili*\n\n"
"/start — Prenota una lavatrice o asciugatrice\n"
"/view — Visualizza le prenotazioni attive\n"
"/free — Libera manualmente una macchina\n"
"/cancel — Annulla l'operazione corrente\n"
"/help — Mostra questo messaggio\n"
)
await update.message.reply_text(text, parse_mode="Markdown")
# ---------------- MAIN ----------------
if __name__ == "__main__":
import platform
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Load persisted bookings on startup
load_bookings()
app = ApplicationBuilder().token(config.BOT_TOKEN).build()
# --- Booking conversation ---
booking_handler = ConversationHandler(
entry_points=[CommandHandler("start", start)],
states={
CHOOSE_TYPE: [MessageHandler(filters.TEXT & ~filters.COMMAND, choose_type)],
CHOOSE_MACHINE: [MessageHandler(filters.TEXT & ~filters.COMMAND, choose_machine)],
DURATION: [MessageHandler(filters.TEXT & ~filters.COMMAND, duration)],
},
fallbacks=[CommandHandler("cancel", cancel)],
)
# --- Free/empty conversation ---
free_handler = ConversationHandler(
entry_points=[CommandHandler("free", free_start)],
states={
EMPTY_CHOOSE_MACHINE: [MessageHandler(filters.TEXT & ~filters.COMMAND, free_choose_machine)],
},
fallbacks=[CommandHandler("cancel", cancel)],
)
app.add_handler(booking_handler)
app.add_handler(free_handler)
app.add_handler(CommandHandler("view", view))
app.add_handler(CommandHandler("help", help_command))
print("🤖 LaundryBot is running...")
app.run_polling()