-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
427 lines (373 loc) · 20.8 KB
/
main.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
from access import Token
import keyboard as kb
import pyrebase_script as pb
import json
import time
from pprint import pprint
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import LabeledPrice, ShippingOption
from telepot.delegate import (
per_invoice_payload, pave_event_space, create_open,
per_message, call)
from datetime import datetime
from emoji import emojize
menu_file = open('menu.json')
menu_json = json.load(menu_file)
menu_dict = json.loads(json.dumps(menu_json))['menu']
orders_file = open('order_list.json')
orders_json = json.load(orders_file)
orders_dict = json.loads(json.dumps(orders_json))
class OrderProcessor(telepot.helper.InvoiceHandler):
def __init__(self, *args, **kwargs):
super(OrderProcessor, self).__init__(*args, **kwargs)
def on_shipping_query(self, msg):
query_id, from_id, invoice_payload = telepot.glance(msg, flavor='shipping_query')
print('Shipping query:')
pprint(msg)
bot.answerShippingQuery(
query_id, True,
shipping_options=[
ShippingOption(id='self_collection', title='Self Collection', prices=[
LabeledPrice(label='self_collection', amount=0)]),
ShippingOption(id='delivery', title='Delivery', prices=[
LabeledPrice(label='delivery', amount=390)])])
def on_pre_checkout_query(self, msg):
query_id, from_id, invoice_payload = telepot.glance(msg, flavor='pre_checkout_query')
print('Pre-Checkout query:')
pprint(msg)
bot.answerPreCheckoutQuery(query_id, True)
def on_chat_message(self, msg):
pprint(msg)
content_type, chat_type, chat_id = telepot.glance(msg)
if content_type == 'successful_payment':
print('Successful payment RECEIVED!!!')
phone_no = msg['successful_payment']['order_info']['phone_number']
name = msg['chat']['username']
prod = msg['successful_payment']['invoice_payload']
current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if str(prod)[:3] == 'CC:':
pprint(msg)
all_items = str(prod)[3:]
all_items_list = all_items.split(':')
all_items_list.pop(len(all_items_list)-1)
for item in all_items_list:
order_id = int(pb.get_num_entry()) + 1
if 'UPSIZE' in item.upper():
pb.push_order(order_id=order_id,
chat_id=int(chat_id),
name=str(name),
phone_no=int(phone_no),
prod=str(item).replace(' Upsize', ''),
current_datetime=current_datetime,
upsize=1)
else:
pb.push_order(order_id=order_id,
chat_id=int(chat_id),
name=str(name),
phone_no=int(phone_no),
prod=str(item),
current_datetime=current_datetime)
bot.sendMessage(chat_id=chat_id, parse_mode='HTML',
text='Hi ' + '<b>' + name + '</b>\n'
+ 'You purchased ' + '<b>' + item + '</b>\n'
+ ' on ' + '<b>' + current_datetime + '</b>\n\n'
+ 'Your order number is ' + str(order_id)
+ '\nThanks for the order!')
for order in orders_dict['orders']:
if chat_id == order['chat_id']:
order['orders'] = []
with open('order_list.json', 'w') as outfile:
json.dump(orders_dict, outfile)
break
else:
order_id = int(pb.get_num_entry()) + 1
if 'UPSIZE' in str(prod).upper():
pb.push_order(order_id=order_id,
chat_id=int(chat_id),
name=str(name),
phone_no=int(phone_no),
prod=str(prod).replace(' Upsize', ''),
current_datetime=current_datetime,
upsize=1)
else:
pb.push_order(order_id=order_id,
chat_id=int(chat_id),
name=str(name),
phone_no=int(phone_no),
prod=str(prod),
current_datetime=current_datetime)
bot.sendMessage(chat_id=chat_id, parse_mode='HTML',
text='Hi ' + '<b>' + name + '</b>\n'
+ 'You purchased ' + '<b>' + prod + '</b>\n'
+ ' on ' + '<b>' + current_datetime + '</b>\n\n'
+ 'Your order number is ' + str(order_id)
+ '\nThanks for the order!')
else:
print('Chat message:')
pprint(msg)
def send_invoice(seed_tuple):
msg = seed_tuple[1]
pprint(msg)
content_type, chat_type, chat_id = telepot.glance(msg)
print(content_type, chat_type, chat_id)
if content_type == 'text':
if msg['text'] in ('/help', '/start'):
bot.sendMessage(chat_id, parse_mode='HTML',
text=emojize(
":hamburger: Hi! You can now order food from <b>NUS McDonald's</b>! \n"
":backhand_index_pointing_down: Below is the list of commands and what they do\n\n"
":white_heavy_check_mark: <b>User's command</b>\n"
"/menu - Display menu and their prices\n"
"/cart - Show items in cart\n"
"/clearCart - Empty your cart\n"
"/order - Checkout items in cart\n"
"/orderStatus - Check status of pending orders\n\n"
":credit_card: Use credit card number <b>4242 4242 4242 4242</b> if you do not have one"
" and would want to test out the bot\n\n"))
elif msg['text'] == '/menu':
bot.sendMessage(chat_id, parse_mode='HTML',
text=emojize(
"<b>Hi, these are the items on the menu.</b> :french_fries:\n\n"
":chicken: /McSpicy - $5.80\n"
":chicken: /DoubleMcSpicy - $7.65\n"
":chicken: /McChicken - $3.95\n"
":cow: /BigMac - $6.00\n"
":cow: /Cheeseburger - $2.80\n"
":cow: /DoubleCheeseburger - $4.60\n"
":fish: /FiletOFish - $4.60\n"
":chicken: /ChickenMcNuggets - $4.90\n"
":chicken: /McWings - $4.90\n\n"
"<b>Upsized</b>\n"
":chicken: /McSpicyUP - $7.30\n"
":chicken: /DoubleMcSpicyUP - $9.15\n"
":chicken: /McChickenUP - $5.45\n"
":cow: /BigMacUP - $7.50\n"
":cow: /CheeseburgerUP - $4.30\n"
":cow: /DoubleCheeseburgerUP - $6.10\n"
":fish: /FiletOFishUP - $6.10\n"
":chicken: /ChickenMcNuggetsUP - $6.40\n"
":chicken: /McWingsUP - $6.40\n"
))
elif msg['text'] == '/order':
for order in orders_dict['orders']:
if chat_id == order['chat_id']:
if len(order['orders']) == 0:
bot.sendMessage(chat_id, text='No item in cart!\n'
'Add them from /menu now!')
break
else:
description = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '\n\n'
this_payload = 'CC:'
for order in orders_dict['orders']:
for item in order['orders']:
description += str(item[0]) + ' (${:.2f})\n'.format(int(item[1])/100)
this_payload += str(item[0]).replace(' ', '_') + ':'
sent = bot.sendInvoice(
chat_id=chat_id,
title='Checkout Cart',
description=description,
payload=this_payload,
provider_token=Token.PAYMENT_PROVIDER_TOKEN,
start_parameter=order['chat_id'],
currency='SGD',
photo_url='https://d1nqx6es26drid.cloudfront.net/app/uploads/2015/06/18104056/ramanda-bundles.png',
prices=[LabeledPrice(label=item[0], amount=item[1]) for order in orders_dict['orders'] for item in order['orders']],
need_shipping_address=True, need_phone_number=True
)
print(sent)
break
else: # no such user in json file
orders_dict['orders'].append({'chat_id': int(chat_id), "orders": []})
with open('order_list.json', 'w') as outfile:
json.dump(orders_dict, outfile)
bot.sendMessage(chat_id, text='No item in cart!\n'
'Add them from /menu now!')
elif msg['text'] == '/orderStatus': # view cart
incomplete_list = pb.get_pending_orders(chat_id=chat_id)
to_sent_str = ''
for item in incomplete_list:
to_sent_str += 'Order: ' + str(item['id']) + '\n'
to_sent_str += item['product'] + '\n\n'
bot.sendMessage(chat_id, text=to_sent_str)
elif msg['text'] == '/cart': # view cart
for order in orders_dict['orders']:
if chat_id == order['chat_id']:
if len(order['orders']) == 0:
bot.sendMessage(chat_id, text='No item in cart!\n'
'Add them from /menu now!')
break
else:
description = '<b>Click</b> /order <b>to checkout!</b>\n\n'
for item in order['orders']:
description += str(item[0]) + ' (${:.2f})\n'.format(int(item[1])/100)
description += '\n'
for item in order['orders']:
description += '/drop_' + str(item[0]).replace(' ', '_') + '\n'
description += '\nEmpty cart: /clearCart'
bot.sendMessage(chat_id, text=description, parse_mode='HTML')
break
else: # no such user in json file
orders_dict['orders'].append({'chat_id': int(chat_id), "orders": []})
with open('order_list.json', 'w') as outfile:
json.dump(orders_dict, outfile)
bot.sendMessage(chat_id, text='No item in cart!\n'
'Add them from /menu now!')
elif msg['text'] == '/clearCart': # empty cart
for order in orders_dict['orders']:
if chat_id == order['chat_id']:
order['orders'] = []
with open('order_list.json', 'w') as outfile:
json.dump(orders_dict, outfile)
bot.sendMessage(chat_id,
text='Cart is empty!\n'
'Start browsing more items at /menu!')
break
elif msg['text'][:4] == '/add': # add individual items to order list
for order in orders_dict['orders']:
if chat_id == order['chat_id']:
if len(order['orders']) == 10:
bot.sendMessage(chat_id, text='Sorry, maximum order is 10 items!\n'
'Drop item(s) or /order now!')
else:
try:
name_to_compare = str(msg['text'])
name_to_compare = name_to_compare[5:]
name_to_compare = name_to_compare.upper()
print(name_to_compare)
for i in menu_dict:
if name_to_compare.replace('UP', '') == str(i['backend_name']).upper():
if msg['text'][-2:].upper() == 'UP':
order['orders'].append([str(i['frontend_name'])+' Upsize', int(i['price_upsize'])])
bot.sendMessage(chat_id, text='Item added to cart! View /cart!\n'
'Continue browsing at /menu!')
break
else:
order['orders'].append([str(i['frontend_name']), int(i['price'])])
bot.sendMessage(chat_id, text='Item added to cart! View /cart!\n'
'Continue browsing at /menu!')
break
else:
bot.sendMessage(chat_id, text='No item added, try again?')
break
with open('order_list.json', 'w') as outfile:
json.dump(orders_dict, outfile)
break
except:
bot.sendMessage(chat_id, text='No item added, try again?')
break
else: # no such user in json file
try:
name_to_compare = str(msg['text'])
name_to_compare = name_to_compare[5:]
name_to_compare = name_to_compare.upper()
print(name_to_compare)
for i in menu_dict:
if name_to_compare.replace('UP', '') == str(i['backend_name']).upper():
if msg['text'][-2:].upper() == 'UP':
orders_dict['orders'].append({'chat_id': int(chat_id), "orders": [[str(i['frontend_name'])+' Upsize', int(i['price_upsize'])]]})
bot.sendMessage(chat_id, text='Item added to cart! View /cart!')
break
else:
orders_dict['orders'].append({'chat_id': int(chat_id), "orders": [[str(i['frontend_name']), int(i['price'])]]})
bot.sendMessage(chat_id, text='Item added to cart! View /cart!')
break
else:
bot.sendMessage(chat_id, text='No item added, try again?')
with open('order_list.json', 'w') as outfile:
json.dump(orders_dict, outfile)
except:
bot.sendMessage(chat_id, text='No item added, try again?')
orders_dict['orders'].append({'chat_id': int(chat_id), "orders": []})
with open('order_list.json', 'w') as outfile:
json.dump(orders_dict, outfile)
elif msg['text'][:5] == '/drop': # drop individual items to order list
for order in orders_dict['orders']:
if chat_id == order['chat_id']:
if len(order['orders']) == 0:
bot.sendMessage(chat_id, text='No item in cart!\n'
'Add them from /menu now!')
else:
try:
name_to_compare = str(msg['text'])
name_to_compare = name_to_compare[6:]
name_to_compare = name_to_compare.replace('_', ' ')
name_to_compare = name_to_compare.upper()
print(name_to_compare)
for i in range(len(order['orders'])):
name_in_dict = order['orders'][i][0]
if 'UPSIZE' in name_to_compare.upper():
if name_to_compare.upper() == str(name_in_dict).upper():
del order['orders'][i]
bot.sendMessage(chat_id, text='Item removed from cart! View /cart')
print(order['orders'])
break
else:
if name_to_compare.upper() == str(name_in_dict).upper():
del order['orders'][i]
bot.sendMessage(chat_id, text='Item removed from cart! View /cart')
print(order['orders'])
break
else:
bot.sendMessage(chat_id, text='No item removed, try again?')
break
with open('order_list.json', 'w') as outfile:
json.dump(orders_dict, outfile)
break
except:
bot.sendMessage(chat_id, text='No item removed, try again?')
break
else: # no such user in json file
bot.sendMessage(chat_id, text='No item removed, try again?')
try:
orders_dict['orders'].append({'chat_id': int(chat_id), "orders": []})
with open('order_list.json', 'w') as outfile:
json.dump(orders_dict, outfile)
except:
pass
else:
name_to_compare = str(msg['text'])
name_to_compare = name_to_compare.replace("/", "")
name_to_compare = name_to_compare.upper()
for i in menu_dict:
if name_to_compare.replace("UP", "") == str(i['backend_name']).upper():
if name_to_compare[-2:] == "UP":
title = i['frontend_name'] + ' Upsize'
label = 'Meal - Upsize'
price = i['price_upsize']
else:
title = i['frontend_name']
label = 'Meal - No Upsize'
price = i['price']
sent = bot.sendInvoice(
chat_id=chat_id,
title=title,
description=i['description'],
payload=title,
provider_token=Token.PAYMENT_PROVIDER_TOKEN,
start_parameter=str(chat_id),
currency='SGD',
photo_url=i['photo_url'],
prices=[LabeledPrice(label=label, amount=price)],
need_shipping_address=True, need_phone_number=True,
reply_markup=kb.custom_inline(price)
)
print(sent)
bot.sendMessage(chat_id, parse_mode='HTML',
text='<b>Add to cart instead?</b>\n'
'Click: /add_{}'.format(name_to_compare))
break
else:
bot.sendMessage(chat_id, reply_markup=kb.default_keyboard,
text='Sorry, there seems to be an error!\n'
'Try out some of the actions below?')
bot = telepot.DelegatorBot(Token.TOKEN, [
(per_message(flavors=['chat']), call(send_invoice)),
pave_event_space()(
per_invoice_payload(), create_open, OrderProcessor, timeout=30,
)
])
print('Listening...')
MessageLoop(bot).run_as_thread()
while 1:
time.sleep(10)