-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
676 lines (482 loc) · 22.3 KB
/
Copy pathbot.py
File metadata and controls
676 lines (482 loc) · 22.3 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# bot.py
# to start the bot - in terminal use "python bot.py"
import os
import django
# ✅ Initialize Django FIRST
# ------------------ Django Setup ------------------
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") # adjust to your settings module
django.setup()
# ------------------ now import the remain -------------------
import re
import logging
from decimal import Decimal
from io import BytesIO
import httpx
from PIL import Image
from asgiref.sync import sync_to_async
# ✅ NOW it's safe to import Django stuff
from shop.services.cart_service import get_or_create_active_cart, add_product_to_cart, get_cart_item
from shop.models import Category, Product, Order, OrderItem, CartItem
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
ApplicationBuilder, CommandHandler, CallbackQueryHandler,
ConversationHandler, MessageHandler, ContextTypes, filters
)
# ------------------ Logging ------------------
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ------------------ Globals ------------------
BOT_TOKEN = os.getenv("BOT_TOKEN")
SITE_URL = os.getenv("SITE_URL", "http://localhost:8000")
# ------------------ REGEX ------------------
PHONE_REGEX = re.compile(r"^\+?\d{7,15}$")
EMAIL_REGEX = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
NAME_REGEX = re.compile(r"^[A-Za-z\s]{2,}$")
# ------------------ Helpers ------------------
async def resize_image_for_telegram(image_path):
"""Return a BytesIO JPEG suitable for Telegram (or None on failure)."""
try:
with Image.open(image_path) as img:
min_size, max_size = 200, 2000
w, h = img.size
if w < min_size or h < min_size:
scale = max(min_size / max(w, 1), min_size / max(h, 1))
img = img.resize((int(w * scale), int(h * scale)))
if w > max_size or h > max_size:
img.thumbnail((max_size, max_size))
bio = BytesIO()
img.convert("RGB").save(bio, format="JPEG")
bio.seek(0)
return bio
except Exception as e:
logger.debug("resize_image_for_telegram failed: %s", e)
return None
async def safe_send_text(chat_id, context: ContextTypes.DEFAULT_TYPE, text, reply_markup=None, parse_mode=None):
"""Send text safely."""
try:
await context.bot.send_message(chat_id=chat_id, text=text, reply_markup=reply_markup, parse_mode=parse_mode)
except Exception as e:
logger.error("Failed to send message to %s: %s", chat_id, e)
async def send_cart_message(chat_id, message_obj, context):
# 1️⃣ Get cart
cart = await get_or_create_active_cart(chat_id) # already async
# 2️⃣ Fetch items with related products
items = await sync_to_async(lambda: list(CartItem.objects.filter(cart=cart).select_related('product')))()
if not items:
try:
await message_obj.edit_text("🛒 Your cart is empty.")
except Exception:
await safe_send_text(chat_id, context, "🛒 Your cart is empty.")
return
lines = []
total = Decimal("0.00")
keyboard = []
for item in items:
subtotal = item.price * item.quantity
total += subtotal
lines.append(f"{item.product.name} x{item.quantity} = ${subtotal:.2f}")
keyboard.append([
InlineKeyboardButton(
f"🛒 {item.product.name} (x{item.quantity})",
callback_data="noop"
)
])
keyboard.append([
InlineKeyboardButton("➕", callback_data=f"inc_{item.product.id}"),
InlineKeyboardButton("➖", callback_data=f"dec_{item.product.id}"),
InlineKeyboardButton("❌", callback_data=f"rm_{item.product.id}")
])
lines.append(f"\n*Total:* ${total:.2f}")
keyboard.append([InlineKeyboardButton("Checkout", callback_data="checkout_now")])
markup = InlineKeyboardMarkup(keyboard)
text = "🛒 *Your Cart:*\n\n" + "\n".join(lines)
try:
await message_obj.edit_text(text, parse_mode="Markdown", reply_markup=markup)
except Exception:
await safe_send_text(chat_id, context, text, reply_markup=markup, parse_mode="Markdown")
# ------------------ Delivery Helper ------------------
async def send_delivery_status(chat_id, order_id, context: ContextTypes.DEFAULT_TYPE):
from delivery.models import Delivery
try:
delivery = await sync_to_async(Delivery.objects.get)(order_id=order_id)
text = (
f"📦 **Order #{order_id} Delivery Status**\n\n"
f"Status: {delivery.status}\n"
f"Current Location: {delivery.current_location}\n"
f"ETA: {delivery.eta or 'Not available'}"
)
await safe_send_text(chat_id, context, text, parse_mode="Markdown")
except Delivery.DoesNotExist:
await safe_send_text(chat_id, context, f"🚨 Delivery info not found for Order #{order_id}")
# ------------------ Commands ------------------
# async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
# await safe_send_text(update.message.chat.id, context, "👋 Welcome to ShopBot!\nUse /shop to browse categories.")
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.message.chat.id
print("MERCHANT_CHAT_ID:", chat_id)
# ---------- 1) Send Shop Logo ----------
logo_path = "static/images/logo.jpg" # put your logo file in static/images folder
try:
if os.path.exists(logo_path):
await context.bot.send_photo(
chat_id=chat_id,
photo=open(logo_path, "rb")
)
except Exception as e:
logger.error(f"Failed to send logo: {e}")
# ---------- 2) Send Shop Description ----------
description = (
"🍏 **FreshMart – Your Daily Fresh Market!**\n\n"
"We offer the freshest high-quality:\n"
"🥬 Vegetables\n"
"🍎 Fruits\n"
"🥚 Eggs\n"
"🥛 Milk\n"
"🚰 Water & Beverages\n"
"🍞 Bread\n"
"🧀 Cheese & Dairy\n"
"🍗 Fresh Chicken\n"
"🥩 Fresh Meat\n"
"🐟 Fish & Seafood\n"
"🥫 Canned Goods\n"
"🛒 Snacks & Biscuits\n"
"🍯 Honey & Jams\n"
"🍚 Rice, Grains & Pasta\n"
"🧼 Home Essentials\n\n"
"Always clean • Always fresh • Always delivered to you 🚚💚"
)
await safe_send_text(chat_id, context, description, parse_mode="Markdown")
# ---------- 3) Invite user to start shopping ----------
welcome = (
"👋 *Welcome!* Thank you for visiting FreshMart.\n\n"
"🛒 To begin shopping, simply click:\n"
"👉 */start*\n"
"or type */shop* to browse categories.\n\n"
"Happy shopping! 🌿"
)
await safe_send_text(chat_id, context, welcome, parse_mode="Markdown")
async def shop(update: Update, context: ContextTypes.DEFAULT_TYPE):
cats = await sync_to_async(list)(Category.objects.all())
if not cats:
await safe_send_text(update.message.chat.id, context, "No categories available yet.")
return
buttons = [[InlineKeyboardButton(c.name, callback_data=f"cat_{c.id}")] for c in cats]
await safe_send_text(update.message.chat.id, context, "Choose category:", reply_markup=InlineKeyboardMarkup(buttons))
async def cart_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.message.chat.id
cart = await sync_to_async(get_or_create_active_cart)(chat_id)
items = await sync_to_async(cart.items.exists)()
if not items:
await safe_send_text(chat_id, context, "🛒 Your cart is empty.")
return
msg = await update.message.reply_text("Loading cart...")
await send_cart_message(chat_id, msg, context)
# Any random text → behave like /start
async def fallback_to_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await safe_send_text(
update.message.chat.id,
context,
"👋 I didn’t understand that.\n\nUse /shop to browse products 🛒"
)
await safe_send_text(update.message.chat.id,context, "👋 Welcome! Let me guide you 👇")
await start(update, context)
# ------------------ Checkout Conversation ------------------
NAME, PHONE, ADDRESS, EMAIL, CONFIRM = range(5)
async def checkout_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
context.user_data['in_conversation'] = True
# Support both message and callback query
if update.message:
chat_id = update.message.chat.id
elif update.callback_query:
chat_id = update.callback_query.message.chat.id
await update.callback_query.answer() # Answer the button to remove "loading" circle
else:
return ConversationHandler.END # Should never happen
from shop.services.cart_service import get_or_create_active_cart
cart = await get_or_create_active_cart(chat_id)
if not cart or not await sync_to_async(cart.items.exists)():
await safe_send_text(chat_id, context, "🛒 Your cart is empty. Add products first.")
return ConversationHandler.END
await safe_send_text(chat_id, context, "Please enter your *full name*:", parse_mode="Markdown")
return NAME
async def checkout_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
name = update.message.text.strip()
if not NAME_REGEX.match(name):
await safe_send_text(update.message.chat.id, context, "❌ Invalid name.\nPlease enter a valid *full name* (letters only):",parse_mode="Markdown" )
return NAME
context.user_data["name"] = name
await safe_send_text(update.message.chat.id, context, "📱 Please enter your phone number:")
return PHONE
async def checkout_phone(update: Update, context: ContextTypes.DEFAULT_TYPE):
phone = update.message.text.strip()
if not PHONE_REGEX.match(phone):
await safe_send_text(update.message.chat.id, context,"❌ Invalid phone number.\n""Please enter a valid number.\n" "Example: +966501234567" )
return PHONE
context.user_data["phone"] = phone
await safe_send_text(update.message.chat.id, context, "📍 Please enter your address:")
return ADDRESS
async def checkout_address(update: Update, context: ContextTypes.DEFAULT_TYPE):
address = update.message.text.strip()
if len(address) < 5:
await safe_send_text(update.message.chat.id, context, "❌ Address is too short.\nPlease enter a valid address:")
return ADDRESS
context.user_data["address"] = address
await safe_send_text(update.message.chat.id,context,"📧 (Optional) Enter your email or type /skip")
return EMAIL
async def checkout_email(update: Update, context: ContextTypes.DEFAULT_TYPE):
email = update.message.text.strip()
if not EMAIL_REGEX.match(email):
await safe_send_text(update.message.chat.id,context,"❌ Invalid email format.\nExample: user@example.com\nOr type /skip" )
return EMAIL
context.user_data["email"] = email
return await checkout_confirm_msg(update, context)
async def skip_email(update: Update, context: ContextTypes.DEFAULT_TYPE):
context.user_data["email"] = None
return await checkout_confirm_msg(update, context)
async def checkout_confirm_msg(src, context: ContextTypes.DEFAULT_TYPE):
data = context.user_data
text = (
"🧾 **Review Your Information**\n\n"
f"👤 Name: {data['name']}\n"
f"📱 Phone: {data['phone']}\n"
f"📍 Address: {data['address']}\n"
f"📧 Email: {data.get('email') or '—'}\n\n"
"Is this information correct?"
)
keyboard = InlineKeyboardMarkup([
[
InlineKeyboardButton("✅ Yes, proceed", callback_data="confirm_checkout"),
InlineKeyboardButton("❌ Cancel", callback_data="cancel_checkout")
]
])
if isinstance(src, Update):
await src.message.reply_text(text, reply_markup=keyboard, parse_mode="Markdown")
else:
await src.edit_message_text(text, reply_markup=keyboard, parse_mode="Markdown")
return CONFIRM
async def checkout_confirm(update: Update, context: ContextTypes.DEFAULT_TYPE):
context.user_data['in_conversation'] = False
query = update.callback_query
await query.answer()
chat_id = query.message.chat.id
data = context.user_data
cart = await get_or_create_active_cart(chat_id)
items = await sync_to_async(list)(cart.items.select_related("product"))
if not items:
await safe_send_text(chat_id, context, "Your cart is empty. Use /shop to start again.")
return ConversationHandler.END
# 1️⃣ Create Django Order
order = await sync_to_async(Order.objects.create)(
chat_id=chat_id,
customer_name=data["name"],
phone=data["phone"],
address=data["address"],
email=data.get("email")
)
total = Decimal("0.00")
for item in items:
subtotal = item.price * item.quantity
total += subtotal
await sync_to_async(OrderItem.objects.create)( order=order,product=item.product, quantity=item.quantity,price=item.price)
order.total = total
await sync_to_async(order.save)()
cart.is_active = False
await sync_to_async(cart.save)()
# 2️⃣ Call Django create_checkout_session (Stripe)
try:
async with httpx.AsyncClient() as client:
resp = await client.post(f"{SITE_URL}/payment/create-checkout-session/{order.id}/")
resp.raise_for_status()
data = resp.json()
pay_url = data.get("url")
keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton("💳 Pay Now", url=pay_url)]
])
await safe_send_text(chat_id, context, f"🛒 Order #{order.id} created! Click below to pay:", reply_markup=keyboard)
except Exception as e:
await safe_send_text(chat_id, context, f"Payment initiation failed: {str(e)}")
return ConversationHandler.END
async def checkout_cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
# 🔄 Reset conversation flag
context.user_data['in_conversation'] = False
# 🧹 Clear checkout data (optional but clean)
for key in ("name", "phone", "address", "email"):
context.user_data.pop(key, None)
keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton("🛒 Continue Shopping", callback_data="shop")],
[InlineKeyboardButton("🧺 View Cart", callback_data="view_cart")]
])
await query.edit_message_text(
"❌ *Checkout cancelled.*\n\nWhat would you like to do next?",
reply_markup=keyboard,
parse_mode="Markdown"
)
return ConversationHandler.END
async def track_order(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.effective_user.id
order = await sync_to_async(Order.objects.filter(chat_id=chat_id).order_by('-created_at').first)()
if not order:
return await update.message.reply_text("You don’t have any orders yet.")
status_map = {
"pending": "⏳ Waiting for confirmation",
"accepted": "🧑🍳 Your order is being prepared",
"shipped": "🚚 Your order is on the way",
"done": "✅ Your order has been delivered",
"cancelled": "❌ Your order was cancelled",
}
text = f"""
📦 *Order Tracking*
Order ID: `{order.id}`
Status: {status_map.get(order.status, 'Unknown')}
Total: {order.total} SAR
Date: {order.created_at.strftime('%Y-%m-%d %H:%M')}
"""
await update.message.reply_text(text, parse_mode="Markdown")
async def my_orders(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.effective_user.id
orders = await sync_to_async(Order.objects.filter)(chat_id=chat_id)
if not orders.exists():
return await update.message.reply_text("You have no orders yet.")
msg = "📦 *Your Previous Orders:*\n\n"
for order in orders.order_by('-created_at')[:10]:
msg += f"""
🆔 Order ID: `{order.id}`
Status: {order.status}
Total: {order.total} SAR
Date: {order.created_at.strftime('%Y-%m-%d')}
--------------------------
"""
await update.message.reply_text(msg, parse_mode="HTML")
# ------------------ Callback Handler --- button_handler ------------------
async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
data = query.data
# Let ConversationHandler handle checkout
if data == "checkout_now":
return # DO NOT handle here, ConversationHandler will catch it
await query.answer()
chat_id = query.message.chat.id
# ---------- Category ----------
if data.startswith("cat_"):
cat_id = data.split("_", 1)[1]
category = await sync_to_async(Category.objects.get)(id=cat_id)
cat_name = category.name
products = await sync_to_async(list)(
Product.objects.filter(category=category, is_active=True)
)
if not products:
await query.edit_message_text("No products in this category.")
return
buttons = [
[InlineKeyboardButton(f"{p.name} - ${p.price}", callback_data=f"prod_{p.id}")]
for p in products
]
await query.edit_message_text(
f"📦 Products in **{cat_name}** category:",
reply_markup=InlineKeyboardMarkup(buttons),
parse_mode="Markdown"
)
return
# ---------- Product ----------
if data.startswith("prod_"):
prod_id = data.split("_", 1)[1]
product = await sync_to_async(Product.objects.get)(id=prod_id)
text = f"*{product.name}*\nPrice: ${product.price}\n\n{product.description or ''}"
buttons = [
[InlineKeyboardButton("➕ Add to cart", callback_data=f"add_{prod_id}")],
[InlineKeyboardButton("Back to categories", callback_data="back_cats")]
]
if getattr(product.image, "path", None) and os.path.exists(product.image.path):
bio = await resize_image_for_telegram(product.image.path)
if bio:
try:
await query.message.reply_photo(photo=bio, caption=text, parse_mode="Markdown", reply_markup=InlineKeyboardMarkup(buttons))
return
except Exception as e:
logger.debug("reply_photo failed: %s", e)
await query.edit_message_text(text, parse_mode="Markdown", reply_markup=InlineKeyboardMarkup(buttons))
return
# ---------- Cart Operations ----------
if data.startswith(("add_", "inc_", "dec_", "rm_")):
op, prod_id = data.split("_", 1)
cart = await get_or_create_active_cart(chat_id)
item = await get_cart_item(cart, prod_id)
if op in ("add", "inc"):
await add_product_to_cart(cart, prod_id, 1)
elif op == "dec" and item:
if item.quantity > 1:
item.quantity -= 1
await sync_to_async(item.save)()
else:
await sync_to_async(item.delete)()
elif op == "rm" and item:
await sync_to_async(item.delete)()
await send_cart_message(chat_id, query.message, context)
return
# ---------- Back to categories ----------
if data == "back_cats":
categories = await sync_to_async(list)(Category.objects.all())
buttons = [[InlineKeyboardButton(c.name, callback_data=f"cat_{c.id}")] for c in categories]
await query.message.reply_text("Choose category:", reply_markup=InlineKeyboardMarkup(buttons))
return
# ---------- Track Order ----------
if data.startswith("track_"):
order_id = data.split("_")[1]
await send_delivery_status(chat_id, order_id, context)
return
# from payment/views.py --- reply_markup -- callback_data
# ---------- Shop button ----------
if data == "shop":
categories = await sync_to_async(list)(Category.objects.all())
buttons = [[InlineKeyboardButton(c.name, callback_data=f"cat_{c.id}")] for c in categories]
await query.message.reply_text("🛒 Choose a category:", reply_markup=InlineKeyboardMarkup(buttons))
return
# ---------- View Cart ----------
if data == "view_cart":
msg = await query.message.reply_text("Loading your cart...")
await send_cart_message(chat_id, msg, context)
return
# ------------------ Startup ------------------
def main():
if not BOT_TOKEN:
print("BOT_TOKEN not found in environment variables.")
return
app = ApplicationBuilder().token(BOT_TOKEN).build()
# --- ConversationHandler for checkout ---
conv_handler = ConversationHandler(
entry_points=[
CommandHandler("checkout", checkout_start),
CallbackQueryHandler(checkout_start, pattern="^checkout_now$")
],
states={
NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, checkout_name)],
PHONE: [MessageHandler(filters.TEXT & ~filters.COMMAND, checkout_phone)],
ADDRESS: [MessageHandler(filters.TEXT & ~filters.COMMAND, checkout_address)],
EMAIL: [
MessageHandler(filters.TEXT & ~filters.COMMAND, checkout_email),
CommandHandler("skip", skip_email)
],
CONFIRM: [
CallbackQueryHandler(checkout_confirm, pattern="^confirm_checkout$"),
CallbackQueryHandler(checkout_cancel, pattern="^cancel_checkout$")
],
},
fallbacks=[CommandHandler("cancel", checkout_cancel)]
)
# --- Add handlers in proper order ( the list must not change )---
# 1️⃣ Conversation handler FIRST
app.add_handler(conv_handler) # MUST come before the generic button handler
# 2️⃣ Command handlers
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("shop", shop))
app.add_handler(CommandHandler("cart", cart_cmd))
# 3️⃣ Callback buttons LAST
app.add_handler(CallbackQueryHandler(button_handler))
# 4️⃣ Text fallback for random text LAST OF ALL
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, fallback_to_start))
print("🤖 Bot running...")
app.run_polling()
if __name__ == "__main__":
main()