-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommands.py
585 lines (436 loc) · 17.7 KB
/
commands.py
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
import os
import pytz
from datetime import datetime
from requests.api import options
from dominos.api import DominosNGClient
from dotenv import load_dotenv
from faunadb.client import FaunaClient
from faunadb import query as q
from telegram import (
ReplyKeyboardMarkup,
InlineKeyboardButton,
InlineKeyboardMarkup,
ReplyKeyboardRemove,
)
from telegram.ext import (
Updater,
ConversationHandler,
)
from utils import geocode
load_dotenv()
fauna_client = FaunaClient(secret=os.getenv("FAUNA_TOKEN"), domain="db.us.fauna.com")
client = DominosNGClient()
updater = Updater(token=os.getenv("TELEGRAM_BOT_TOKEN"), use_context=True)
dispatcher = updater.dispatcher
CONFIRM_ADDRESS, SAVE_ADDRESS, ADDRESS_OR_LOCATION, FIND_STORES, MENU, SUBMENU, ADD_TO_CART = range(7)
# Main Functions
def start(update, context):
'''
This function receives and saves the user's details and sends a welcome message
'''
chat_id = update.effective_chat.id
name = update.message.chat.first_name or update.message.chat.username
try:
user = fauna_client.query(q.get(q.match(q.index("id"), chat_id)))
except:
user = fauna_client.query(q.create(q.collection("users"), {
"data": {
"id": chat_id,
"name": name,
"address": "",
"latitude": "",
"longitude": "",
"date": datetime.now(pytz.UTC)
}
}))
context.user_data["user_id"] = user["ref"].id()
msg = f"Hello {name},\nWelcome to the unofficial bot for Domino's Pizza Nigeria.\n"\
"My name is John and i'll be your botler\n\n"\
"/set_address To set your address\n"\
"/start_order To start order\n"\
"/cart To view your cart items\n"\
"/update_address To update address details\n"\
"/recent_orders To get your recent orders"
context.bot.send_message(chat_id=chat_id, text=msg)
def set_address(update, context):
'''
This function is used to request the user's address
'''
chat_id = update.effective_chat.id
name = update.message.chat.first_name or update.message.chat.username
try:
user = fauna_client.query(q.get(q.match(q.index("id"), chat_id)))
except:
user = fauna_client.query(q.create(q.collection("users"), {
"data": {
"id": chat_id,
"name": name,
"address": "",
"latitude": "",
"longitude": "",
"date": datetime.now(pytz.UTC)
}
}))
context.user_data["user_id"] = user["ref"].id()
msg = "Type your address in this format: [Street number], [Street name], [City]\n"\
"E.g 49, Kunle Street, Lagos"
context.bot.send_message(chat_id=chat_id, text=msg)
return CONFIRM_ADDRESS
def confirm_address(update, context):
'''
This function receives the user's address and checks with Google API.
Then asks user to confirm the address
'''
chat_id = update.effective_chat.id
address = update.message.text
try:
# Check address with Google API
address = geocode(address)
if address:
# Asks user to confirm
msg = f"{address['address']}\n\nIs this your address. (YES/NO)?"
context.user_data['address'] = address['address']
context.user_data['latitude'] = address['latitude']
context.user_data['longitude'] = address['longitude']
reply_keyboard = [['YES','NO']]
markup = ReplyKeyboardMarkup(reply_keyboard)
context.bot.send_message(chat_id=chat_id, text=msg, reply_markup=markup)
return SAVE_ADDRESS
else:
context.bot.send_message(chat_id=chat_id, text="Address Not Found. Try setting another address.")
return ConversationHandler.END
except:
context.bot.send_message(chat_id=chat_id, text="Address Not Found. Try setting another address")
return ConversationHandler.END
def save_address(update, context):
'''
If the user's address is confirmed, it is saved to the DB
'''
chat_id = update.effective_chat.id
choice = update.message.text
address = context.user_data['address']
latitude = context.user_data['latitude']
longitude = context.user_data['longitude']
if choice.lower() == 'yes':
# Updates user's address to DB
fauna_client.query(q.update(q.ref(
q.collection("users"), context.user_data["user_id"]),
{
"data": {
"address": address,
"latitude": latitude,
"longitude": longitude
}
}
))
msg = "Your address has been saved."
elif choice.lower() == 'no':
msg = "Your address wasn't found, try another address keyword"
else:
msg = "Unrecognized reply. Try YES or NO"
context.bot.send_message(chat_id=chat_id, text=msg, reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
def start_order(update, context):
'''
This function starts the order converstaion
'''
chat_id = update.effective_chat.id
msg = "Do you want to use your saved address or current location ?"
reply_keyboard = [
[
InlineKeyboardButton(
text="Saved Address",
callback_data="Saved Address"
),
InlineKeyboardButton(
text="Current Location",
callback_data="Current Location"
)
]
]
markup = InlineKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
context.bot.send_message(chat_id=chat_id, text=msg, reply_markup=markup)
return ADDRESS_OR_LOCATION
def address_or_location(update, context):
'''
This function receives the user's location choice and returns the nearby stores
'''
chat_id = update.callback_query.message.chat.id
if update.callback_query.data.lower() == "saved address":
user = fauna_client.query(q.get(q.match(q.index("id"), chat_id)))
if user['data']['address']:
stores = client.findNearbyStoresFromLocation(user['data']['latitude'], user['data']['longitude'])
context.user_data['latitude'] = user['data']['latitude']
context.user_data['longitude'] = user['data']['longitude']
for store in stores:
keyboard = [
InlineKeyboardButton("Carryout", callback_data=f"Carryout_{store['StoreID']}")
]
if store['IsDeliveryStore']=="true":
keyboard = [
InlineKeyboardButton("Delivery", callback_data=f"Delivery_{store['StoreID']}"),
InlineKeyboardButton("Carryout", callback_data=f"Carryout_{store['StoreID']}")
]
reply_markup = InlineKeyboardMarkup([keyboard])
msg = f"{store['StoreName']}\n{store['StreetName']}, {store['City']}\n{store['Phone']}"\
f"\n\nService Hours: \n\nDelivery: \n{store['ServiceHoursDescription']['Delivery']}"\
f"\n\nCarryout: \n{store['ServiceHoursDescription']['Carryout']}"
context.bot.send_message(chat_id=chat_id, text = msg, reply_markup=reply_markup)
return MENU
else:
msg = "You don't have any saved address\n/set_address To save your address"
context.bot.send_message(chat_id=chat_id, text=msg)
return ConversationHandler.END
elif update.callback_query.data.lower() == "current location":
msg = "Send your current location\n\n"\
"Don't know how to send location? Check here: https://telegram.org/blog/live-locations"
context.bot.send_message(chat_id=chat_id, text=msg)
return FIND_STORES
else:
context.bot.send_message(chat_id=chat_id, text="Unrecognized Reply\n\n/start_order To start order")
return ConversationHandler.END
def location(update, context):
'''
This function receives the user's current location and returns nearby stores
'''
chat_id = update.effective_chat.id
location = update.message.location
context.user_data['latitude'] = location.latitude
context.user_data['longitude'] = location.longitude
stores = client.findNearbyStoresFromLocation(location.latitude, location.longitude)
for store in stores:
keyboard = [
InlineKeyboardButton("Carryout", callback_data=f"Carryout_{store['StoreID']}")
]
if store['IsDeliveryStore']=="true":
keyboard = [
InlineKeyboardButton("Delivery", callback_data=f"Delivery_{store['StoreID']}"),
InlineKeyboardButton("Carryout", callback_data=f"Carryout_{store['StoreID']}")
]
reply_markup = InlineKeyboardMarkup([keyboard])
msg = f"{store['StoreName']}\n{store['StreetName']}, {store['City']}\n{store['Phone']}"\
f"\n\nService Hours: \n\nDelivery: \n{store['ServiceHoursDescription']['Delivery']}"\
f"\n\nCarryout: \n{store['ServiceHoursDescription']['Carryout']}"
context.bot.send_message(chat_id=chat_id, text = msg, reply_markup=reply_markup)
return MENU
def menu(update, context):
'''
This function returns the store menu
'''
chat_id = update.effective_chat.id
query = update.callback_query
query.answer()
# This will define which button the user tapped on (from what you assigned to "callback_data"):
choice = query.data
if "Delivery" in choice or "Carryout" in choice:
choice = choice.split('_')
order_type = choice[0]
store_id = choice[1]
context.user_data['order_type'] = order_type
context.user_data['store_id'] = store_id
menu = client.storemenu(store_id)
productTypes = []
for key, product in menu['Products'].items():
productTypes.append(product.get('ProductType').upper())
productTypes = list(set(productTypes))
for category in productTypes:
msg = f"{category.upper()}"
keyboard = [
InlineKeyboardButton("See Products", callback_data=f"CATEGORY_{category}"),
]
reply_markup = InlineKeyboardMarkup([keyboard])
url = f'images/{category.lower()}.png'
if category.lower() == "papotas":
url = "images/sides.png"
context.bot.send_photo(chat_id=chat_id, photo=open(url, 'rb'), caption=msg, reply_markup=reply_markup)
return SUBMENU
def sub_menu(update, context):
'''
This function returns a menu for a given category
'''
print("submenu")
chat_id = update.callback_query.message.chat.id
choice = update.callback_query.data.split('_')
if choice[0] == 'CATEGORY':
category = choice[1]
store_id = context.user_data['store_id']
menu = client.storemenu(store_id)
for key, item in menu['Products'].items():
if item.get('ProductType').upper() == category:
for variant in item.get('Variants'):
product = menu['Variants'][variant]
name = product['Name']
price = product['Price']
keyboard = [
InlineKeyboardButton("Add To Cart", callback_data=f"addToCart_{product['Code']}")
]
msg = f"{name}\nNGN {price}"
url = f"https://cache.dominos.com/olo/6_64_5/assets/build/market/NG/_en/images/img/products/larges/{product['ProductCode']}.jpg"
reply_markup = InlineKeyboardMarkup([keyboard])
context.bot.send_photo(chat_id=chat_id, photo=url, caption=msg, reply_markup=reply_markup)
return ADD_TO_CART
def add_to_cart(update, context):
'''
This function adds an item to the cart or increases its quantity
'''
print("add to cart")
chat_id = update.callback_query.message.chat.id
reply = update.callback_query.data
product_code = reply.split("_")[1]
store_id = context.user_data['store_id']
order_type = context.user_data['order_type'] or 'Carryout'
try:
context.user_data['id']
except:
context.user_data['id'] = 0
store = client.getStoreDetails(store_id)
streetName = store['StreetName']
city = store['City']
try:
latitude = context.user_data['latitude']
longitude = context.user_data['longitude']
except:
user = fauna_client.query(q.get(q.match(q.index("id"), chat_id)))
latitude = user['data']['latitude']
longitude = user['data']['longitude']
'''
options = {
"D": {
"1/1": "1"
},
"C": {
"1/1": "1"
},
"I": {
"1/1": "1"
},
"M": {
"1/1": "1"
},
"N": {
"1/1": "1"
},
"X": {
"1/1": "1"
}
}
'''
options = {}
try:
cart = fauna_client.query(q.get(q.match(q.index("customer_id"), chat_id)))
except:
cart = fauna_client.query(q.create(q.collection("cart"), {
"data": {
"customer_id": chat_id,
"products": [],
"store_id": store_id,
"order_id" : "",
"order_type": order_type,
"date": datetime.now(pytz.UTC)
}
}))
ref = cart['ref'].id()
cart = cart['data']['products']
new_product = {
"Code": product_code,
"Qty": 1,
"ID": 1,
"isNew": True,
"Options": options
}
# Checks if product is already in cart
for product in cart:
if product['Code'] == new_product['Code']:
product['Qty'] += 1
break
else:
context.user_data['id'] += 1
new_product["ID"] = context.user_data['id']
cart.append(new_product)
orderID = context.user_data.get('orderID',"")
try:
order_id = client.addToCart(
store_id=store_id,
store_city=city,
store_street=streetName,
latitude=latitude,
longitude=longitude,
products=cart,
orderID=orderID,
order_type=order_type,
)
context.user_data['orderID'] = order_id
fauna_client.query(q.update(q.ref(
q.collection("cart"), ref),
{
"data": {
"products": cart,
"order_id": order_id
}
}
))
msg = f'Product Added\n\nSee Your Cart /cart'
except:
msg = "Something went wrong, try again later."
context.bot.send_message(chat_id=chat_id, text = msg)
def view_cart(update, context):
'''
View Cart Items
'''
chat_id = update.effective_chat.id
try:
cart = fauna_client.query(q.get(q.match(q.index("customer_id"), chat_id)))
orderID = cart['data']['order_id']
store_id = cart['data']['store_id']
order_type = cart['data']['order_type']
products = cart['data']['products']
store = client.getStoreDetails(store_id)
streetName = store['StreetName']
city = store['City']
try:
latitude = context.user_data['latitude']
longitude = context.user_data['longitude']
except:
user = fauna_client.query(q.get(q.match(q.index("id"), chat_id)))
latitude = user['data']['latitude']
longitude = user['data']['longitude']
cart_summary = client.priceOrder(
store_id=store_id,
store_city=city,
store_street=streetName,
latitude=latitude,
longitude=longitude,
products=products,
orderID=orderID,
order_type=order_type,
)
order_id = f"Order ID: {cart_summary['Order']['OrderID']}\n"
for product in cart_summary['Order']['Products']:
print(product)
cart_item = f"{product['ID']}. {product['Name']} "\
f"(x{product['Qty']})\nAmount: NGN {product['Amount']}"
keyboard = [
InlineKeyboardButton("Remove from Cart", callback_data=f"{product['Code']}")
]
reply_markup = InlineKeyboardMarkup([keyboard])
context.bot.send_message(chat_id=chat_id, text=cart_item, reply_markup=reply_markup)
msg = f"Amount: NGN {cart_summary['Order']['Amounts']['Menu']}\nTax: NGN {cart_summary['Order']['Amounts']['Tax']}\n"\
f"Discount: NGN {cart_summary['Order']['Amounts']['Discount']}\n\n"\
f"Total: NGN {cart_summary['Order']['Amounts']['Payment']}"
keyboard = [
InlineKeyboardButton("Checkout", callback_data=f"Checkout_{cart_summary['Order']['OrderID']}")
]
reply_markup = InlineKeyboardMarkup([keyboard])
context.bot.send_message(chat_id=chat_id, text=msg, reply_markup=reply_markup)
except:
msg = "Your cart is empty\n\n/start_order To start your order"
context.bot.send_message(chat_id=chat_id, text=msg)
# Control
def cancel(update, context) -> int:
update.message.reply_text(
'Cancelled.',
reply_markup=ReplyKeyboardRemove()
)
return ConversationHandler.END
def common_message(update, context):
pass