-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
471 lines (386 loc) · 20.7 KB
/
Copy pathmain.py
File metadata and controls
471 lines (386 loc) · 20.7 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import os
import logging
from datetime import datetime
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes, ConversationHandler
from DeviceShare import SimpleDeviceShareBot
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
BOT_TOKEN = os.getenv('BOT_TOKEN')
ADMIN_USER_ID = int(os.getenv('ADMIN_USER_ID', "0")) if os.getenv('ADMIN_USER_ID') else None
bot_instance = SimpleDeviceShareBot()
WAITING_USERNAME, WAITING_WORKING_DAYS = range(2)
WORKING_DAYS = {"monday": 0, "mon": 0, "1": 0, "tuesday": 1, "tue": 1, "2": 1, "wednesday": 2, "wed": 2, "3": 2, "thursday": 3, "thu": 3, "4": 3, "friday": 4, "fri": 4, "5": 4}
WORKING_DAYS_NAMES = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
def safe_reply(update, text, reply_markup=None):
if update.message:
return update.message.reply_text(text, reply_markup=reply_markup)
elif update.callback_query:
return update.callback_query.edit_message_text(text, reply_markup=reply_markup)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
if user_id in bot_instance.users:
keyboard = [
[InlineKeyboardButton("📋 List Available Devices", callback_data="list_devices")],
[InlineKeyboardButton("📅 My Schedule", callback_data="my_schedule")],
[InlineKeyboardButton("📊 My Stats", callback_data="my_stats")],
[InlineKeyboardButton("🗑️ Delete Profile", callback_data="delete_profile")],
]
if ADMIN_USER_ID and str(ADMIN_USER_ID) == user_id:
keyboard.append([InlineKeyboardButton("🔧 Admin: Add User", callback_data="admin_add_user")])
reply_markup = InlineKeyboardMarkup(keyboard)
user = bot_instance.users[user_id]
welcome_msg = f"Welcome back, {user['username']}!\n\n"\
f"📍 Device: {bot_instance.get_device_location()}\n"\
f"📊 Today's usages: {len([u for u in bot_instance.usages.get('user_usages', {}).get(user_id, []) if u.get('date') == datetime.now().strftime('%Y-%m-%d')])}/2\n\n"\
"What would you like to do?"
await safe_reply(update, welcome_msg, reply_markup)
else:
keyboard = [
[InlineKeyboardButton("🚀 Register Now", callback_data="register")],
[InlineKeyboardButton("❓ Help", callback_data="help")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
welcome_text = (
"Welcome to SimpleDeviceShare! 🚀\n\n"
"This bot helps you track and share a physical device among team members.\n\n"
"Features:\n"
"• Request device usage (max 2/day)\n"
"• Track device location\n"
"• Admin oversight\n\n"
"To get started, you need to register with your username and working days."
)
await safe_reply(update, welcome_text, reply_markup)
async def register(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
if user_id in bot_instance.users:
keyboard = [
[InlineKeyboardButton("✅ Yes, Re-register", callback_data="confirm_reregister")],
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_reregister")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
user = bot_instance.users[user_id]
await safe_reply(update, f"⚠️ You are already registered as: {user['username']}\n\nRe-registering will delete your current profile. Continue?", reply_markup=reply_markup)
return ConversationHandler.END
await safe_reply(update, "Let's start the registration process! 🚀\n\nPlease enter your username:")
return WAITING_USERNAME
async def handle_username(update: Update, context: ContextTypes.DEFAULT_TYPE):
username = update.message.text.strip()
if len(username) < 2:
await update.message.reply_text("Username must be at least 2 characters long. Please try again:")
return WAITING_USERNAME
context.user_data['username'] = username
keyboard = []
for i, day_name in enumerate(WORKING_DAYS_NAMES):
keyboard.append([InlineKeyboardButton(f"{i+1}. {day_name}", callback_data=f"select_day_{i}")])
keyboard.append([InlineKeyboardButton("✅ Done Selecting", callback_data="done_selecting_days")])
reply_markup = InlineKeyboardMarkup(keyboard)
context.user_data['selected_days'] = []
await update.message.reply_text(f"Great! Your username is: {username}\n\nNow, please select your working days (Monday-Friday only):", reply_markup=reply_markup)
return WAITING_WORKING_DAYS
async def complete_registration(update, context, working_days):
user_id = str(update.effective_user.id)
username = context.user_data['username']
if not ADMIN_USER_ID:
bot_instance.users[user_id] = {
'username': username,
'working_days': working_days,
'registration_time': datetime.now().isoformat()
}
keyboard = [[InlineKeyboardButton("🏠 Main Menu", callback_data="main_menu")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await safe_reply(update, "Registration completed successfully! ✅\n\nYou can now use the bot!", reply_markup=reply_markup)
else:
bot_instance.pending_users[user_id] = {
'username': username,
'working_days': working_days,
'registration_time': datetime.now().isoformat()
}
keyboard = [
[InlineKeyboardButton("✅ Approve", callback_data=f"approve_{user_id}"),
InlineKeyboardButton("❌ Deny", callback_data=f"deny_{user_id}")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
day_names = [WORKING_DAYS_NAMES[day] for day in working_days]
admin_message = f"🔔 New Registration Request:\n\n🆔 User ID: {user_id}\n👤 Username: {username}\n📅 Working Days: {', '.join(day_names)}\n📝 Registration Time: {datetime.now().strftime('%Y-%m-%d %H:%M')}"
await context.bot.send_message(chat_id=ADMIN_USER_ID, text=admin_message, reply_markup=reply_markup)
await safe_reply(update, "Registration submitted successfully! ✅\n\nYour registration is pending admin approval. You will be notified once it's approved or denied.")
return ConversationHandler.END
async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
if query.data == "main_menu":
return await start(update, context)
elif query.data == "register":
return await register(update, context)
elif query.data == "help":
help_text = """🤖 SimpleDeviceShare Bot - Help
📋 Available commands:
/start - Start the bot and show main menu
/register - Register for access
/help - Show this help message
📖 How it works:
1. Register with your username and working days (Mon-Fri only)
2. Request device usage when available (max 2 per day)
3. Track device location with take/return buttons
4. Admins can manage users and view logs
🔒 Features:
• Daily usage limits reset at midnight
• Automatic overdue notifications
• Admin oversight and user management
• All data is in-memory (demo only)
💡 Note: This is a demo bot for educational purposes."""
keyboard = [[InlineKeyboardButton("🏠 Main Menu", callback_data="main_menu")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(help_text, reply_markup=reply_markup)
elif query.data == "list_devices":
user_id = str(query.from_user.id)
if user_id not in bot_instance.users:
await query.edit_message_text("❌ You need to register first.")
return
if not bot_instance.can_user_use_device(user_id):
await query.edit_message_text("❌ You have reached your daily limit of 2 device usages. Try again tomorrow.")
return
keyboard = [
[InlineKeyboardButton("📱 Take Device", callback_data="take_device")],
[InlineKeyboardButton("🔙 Back", callback_data="main_menu")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
f"📋 Device Status:\n\n"
f"📍 Current Location: {bot_instance.get_device_location()}\n"
f"📊 Your usages today: {len([u for u in bot_instance.usages.get('user_usages', {}).get(user_id, []) if u.get('date') == datetime.now().strftime('%Y-%m-%d')])}/2\n\n"
f"Click 'Take Device' to request usage.",
reply_markup=reply_markup
)
elif query.data == "take_device":
user_id = str(query.from_user.id)
if bot_instance.device_status['location'] == 'base':
bot_instance.log_device_action(user_id, 'take')
bot_instance.add_usage(user_id)
keyboard = [
[InlineKeyboardButton("📱 Return Device", callback_data="return_device")],
[InlineKeyboardButton("🔙 Back", callback_data="main_menu")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
"✅ Device taken successfully!\n\n"
"You now have the device. Remember to return it within 2 hours.",
reply_markup=reply_markup
)
else:
await query.edit_message_text("❌ Device is currently with another user.")
elif query.data == "return_device":
user_id = str(query.from_user.id)
if bot_instance.device_status['user_id'] == user_id:
bot_instance.log_device_action(user_id, 'return')
keyboard = [[InlineKeyboardButton("🔙 Back", callback_data="main_menu")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
"✅ Device returned successfully!\n\n"
"Thank you for returning the device on time.",
reply_markup=reply_markup
)
else:
await query.edit_message_text("❌ You don't have the device to return.")
elif query.data == "my_schedule":
user_id = str(query.from_user.id)
if user_id not in bot_instance.users:
await query.edit_message_text("❌ You need to register first.")
return
user = bot_instance.users[user_id]
day_names = [WORKING_DAYS_NAMES[day] for day in user['working_days']]
message = f"📅 Your Schedule:\n\n"
message += f"👤 Username: {user['username']}\n"
message += f"🏢 Working days: {', '.join(day_names)}\n"
message += f"📝 Today is your working day: {'✅' if bot_instance.is_working_day(user_id) else '❌'}"
keyboard = [[InlineKeyboardButton("🔙 Back", callback_data="main_menu")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(message, reply_markup=reply_markup)
elif query.data == "my_stats":
user_id = str(query.from_user.id)
if user_id not in bot_instance.users:
await query.edit_message_text("❌ You need to register first.")
return
stats = bot_instance.get_user_stats(user_id)
if stats:
message = f"📊 Your Statistics:\n\n"
message += f"👤 Username: {stats['username']}\n"
message += f"📅 Today's usages: {stats['today_usages']}/2\n"
message += f"📊 Remaining today: {stats['remaining']}\n"
message += f"📈 Total usages: {stats['total_usages']}"
else:
message = "❌ Unable to get statistics."
keyboard = [[InlineKeyboardButton("🔙 Back", callback_data="main_menu")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(message, reply_markup=reply_markup)
elif query.data == "delete_profile":
user_id = str(query.from_user.id)
if user_id not in bot_instance.users:
await query.edit_message_text("❌ You don't have a profile to delete.")
return
user = bot_instance.users[user_id]
keyboard = [
[InlineKeyboardButton("🗑️ Yes, Delete My Profile", callback_data="confirm_delete_profile")],
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_delete_profile")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
f"⚠️ Are you sure you want to delete your profile?\n\n"
f"👤 Username: {user['username']}\n\n"
f"This action cannot be undone!",
reply_markup=reply_markup
)
elif query.data == "confirm_delete_profile":
user_id = str(query.from_user.id)
username = bot_instance.delete_profile(user_id)
keyboard = [
[InlineKeyboardButton("🚀 Register Again", callback_data="register")],
[InlineKeyboardButton("❓ Help", callback_data="help")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
f"✅ Profile deleted successfully!\n\n"
f"Goodbye {username}! You can register again anytime.",
reply_markup=reply_markup
)
elif query.data == "cancel_delete_profile":
return await start(update, context)
# Admin callbacks
elif query.data.startswith("approve_"):
if not ADMIN_USER_ID or query.from_user.id != ADMIN_USER_ID:
await query.edit_message_text("❌ Unauthorized access.")
return
user_id = query.data.split('_', 1)[1]
if bot_instance.approve_user(user_id):
keyboard = [[InlineKeyboardButton("🏠 Main Menu", callback_data="main_menu")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(
chat_id=int(user_id),
text="🎉 Your registration has been approved! You can now use the bot.",
reply_markup=reply_markup
)
await query.edit_message_text(f"✅ Approved registration for user {user_id}")
else:
await query.edit_message_text("❌ User not found in pending registrations.")
elif query.data.startswith("deny_"):
if not ADMIN_USER_ID or query.from_user.id != ADMIN_USER_ID:
await query.edit_message_text("❌ Unauthorized access.")
return
user_id = query.data.split('_', 1)[1]
if bot_instance.deny_user(user_id):
keyboard = [
[InlineKeyboardButton("🚀 Try Again", callback_data="register")],
[InlineKeyboardButton("❓ Help", callback_data="help")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(
chat_id=int(user_id),
text="❌ Your registration has been denied. Please contact the administrator for more information.",
reply_markup=reply_markup
)
await query.edit_message_text(f"❌ Denied registration for user {user_id}")
else:
await query.edit_message_text("❌ User not found in pending registrations.")
# Working day selection callbacks
elif query.data.startswith("select_day_"):
day_index = int(query.data.split("_")[2])
if 'selected_days' not in context.user_data:
context.user_data['selected_days'] = []
if day_index in context.user_data['selected_days']:
context.user_data['selected_days'].remove(day_index)
else:
context.user_data['selected_days'].append(day_index)
keyboard = []
for i, day_name in enumerate(WORKING_DAYS_NAMES):
selected = "✅" if i in context.user_data['selected_days'] else ""
keyboard.append([InlineKeyboardButton(f"{selected} {i+1}. {day_name}", callback_data=f"select_day_{i}")])
keyboard.append([InlineKeyboardButton("✅ Done Selecting", callback_data="done_selecting_days")])
reply_markup = InlineKeyboardMarkup(keyboard)
selected_names = [WORKING_DAYS_NAMES[i] for i in context.user_data['selected_days']]
selected_text = f"Selected: {', '.join(selected_names)}" if selected_names else "None selected"
await query.edit_message_text(
f"Select your working days (Monday-Friday only):\n\n{selected_text}",
reply_markup=reply_markup
)
elif query.data == "done_selecting_days":
if 'selected_days' not in context.user_data or not context.user_data['selected_days']:
await query.answer("Please select at least one working day!", show_alert=True)
return
working_days = context.user_data['selected_days']
await query.edit_message_text("Processing your registration...")
return await complete_registration(update, context, working_days)
# Re-registration callbacks
elif query.data == "confirm_reregister":
user_id = str(query.from_user.id)
if user_id in bot_instance.users:
del bot_instance.users[user_id]
await query.edit_message_text("Profile deleted. Let's start fresh! 🚀\n\nPlease enter your username:")
context.user_data['in_registration'] = True
return WAITING_USERNAME
elif query.data == "cancel_reregister":
return await start(update, context)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
help_text = """🤖 SimpleDeviceShare Bot - Help
📋 Available commands:
/start - Start the bot and show main menu
/register - Register for access
/help - Show this help message
📖 How it works:
1. Register with your username and working days (Mon-Fri only)
2. Request device usage when available (max 2 per day)
3. Track device location with take/return buttons
4. Admins can manage users and view logs
🔒 Features:
• Daily usage limits reset at midnight
• Automatic overdue notifications
• Admin oversight and user management
• All data is in-memory (demo only)
💡 Note: This is a demo bot for educational purposes."""
keyboard = [[InlineKeyboardButton("🏠 Main Menu", callback_data="main_menu")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(help_text, reply_markup=reply_markup)
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Registration cancelled.")
return ConversationHandler.END
def main():
if not BOT_TOKEN:
print("❌ ERROR: BOT_TOKEN environment variable is not set!")
print("Please set the BOT_TOKEN environment variable in your Railway dashboard.")
return
print("🚀 Starting SimpleDeviceShare Bot...")
print(f"📊 Admin User ID: {ADMIN_USER_ID if ADMIN_USER_ID else 'Not set'}")
try:
application = Application.builder().token(BOT_TOKEN).build()
# Add conversation handler for registration
conv_handler = ConversationHandler(
entry_points=[
CommandHandler('register', register),
CallbackQueryHandler(handle_callback, pattern="^register$"),
CallbackQueryHandler(handle_callback, pattern="^confirm_reregister$")
],
states={
WAITING_USERNAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_username)],
WAITING_WORKING_DAYS: [
CallbackQueryHandler(handle_callback, pattern="^(select_day_|done_selecting_days).*")
],
},
fallbacks=[
CommandHandler('cancel', cancel),
CallbackQueryHandler(handle_callback, pattern="^cancel_.*")
],
allow_reentry=True,
)
application.add_handler(conv_handler)
application.add_handler(CallbackQueryHandler(handle_callback))
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
print("✅ Bot handlers configured successfully")
print("🤖 Starting bot polling...")
application.run_polling(allowed_updates=Update.ALL_TYPES)
except Exception as e:
print(f"❌ Error starting bot: {e}")
logger.error(f"Bot startup error: {e}")
raise
if __name__ == '__main__':
main()