-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
4853 lines (3800 loc) · 214 KB
/
app.py
File metadata and controls
4853 lines (3800 loc) · 214 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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import unicode_literals
import os
import sys
import math
import random
import time
import re
import requests
import urllib
import urllib.request
import Database
import unshortenit
import json
import apiai
import wikipedia
from argparse import ArgumentParser
from flask import Flask, request, abort
from bs4 import BeautifulSoup
from datetime import timedelta
from datetime import datetime
from xml.etree import ElementTree
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError, LineBotApiError,
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
SourceUser, SourceGroup, SourceRoom,
TemplateSendMessage, ConfirmTemplate, MessageTemplateAction,
ButtonsTemplate, URITemplateAction, PostbackTemplateAction,
CarouselTemplate, CarouselColumn, PostbackEvent,
StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,
ImageMessage, VideoMessage, AudioMessage,
UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent,
AudioSendMessage
)
from lines_collection import Lines, Labels, Picture
app = Flask(__name__)
channel_secret = "9b665635f2f8e005e0e9eed13ef18124"
channel_access_token = "ksxtpzGYTb1Nmbgx8Nj8hhkUR5ZueNWdBSziqVlJ2fPNblYeXV7/52HWvey/MhXjgtbml0LFuwQHpJHCP6jN7W0gaKZVUOlA88AS5x58IhqzLZ4Qt91cV8DhXztok9yyBQKAOSxh/uli4cP4lj+2YQdB04t89/1O/w1cDnyilFU="
api_ai_access_token = '4ead94fa71234f82af81f8e92e72962a'
api_ai_access_token_megumi_II = "0e51518979fe4d7eba6b09d4d5ae0d41"
line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)
userlist = Database.userlist
proxies = Database.proxies
userlist_update_count = 0
tag_notifier_on = True
MEGUMI_ONLINE = True
@app.route("/callback", methods=['POST'])
def callback():
""" Get X-Line-Signature header value """
global user_id, user_name
signature = request.headers['X-Line-Signature']
# Get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# Try to get user's id
try:
user_id = json.loads(body)["events"][0]["source"]["userId"]
except:
user_id = ""
# Try to get user's name
try:
user_name = line_bot_api.get_profile(user_id).display_name
except:
user_name = "someone"
# Handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK'
def get_receiver_addr(event):
""" Get the address (source of event) weather it's group or personal chat """
# Enable calling from all functions and methods
global address
# If the event was sent from a group
if isinstance(event.source, SourceGroup):
address = event.source.group_id
# If the event was sent from a chat room
elif isinstance(event.source, SourceRoom):
address = event.source.room_id
# If the event was sent from a personal chat
else:
address = event.source.user_id
return address
def update_user_list(event):
""" Function to notify if the userlist is updated TEMPORARILY """
global userlist, userlist_update_count
# If the add event come from personal chat
if isinstance(event.source, SourceUser):
# Get the list count before update
userlist_init_count = len(userlist.keys())
try:
# Get the user data
userlist.update({user_id: user_name})
# If there's an update
if len(userlist.keys()) != userlist_init_count:
userlist_update_count = userlist_update_count + 1
if userlist_update_count >= 1: # stay 1 until heroku upgraded (due to 30 mins inactivity)
# Send report to Dev (reminder to update the list)
report = Lines.dev_mode_userlist("notify update userlist") % (str(userlist_update_count))
command = "megumi dev mode print userlist"
buttons_template = ButtonsTemplate(title="Update userlist", text=report, actions=[
PostbackTemplateAction(label=Labels.print_userlist(), data=command)
])
template_message = TemplateSendMessage(alt_text=report, template=buttons_template)
for dev_user in Database.devlist:
line_bot_api.push_message(dev_user, template_message)
# Send report contain new user only
report = str("New user : \n'"+user_id+"': '"+user_name+"'")
for dev_user in Database.devlist:
line_bot_api.push_message(dev_user, TextSendMessage(text=report))
except Exception as exception_detail:
function_name = "Sending Userlist notification"
OtherUtil.random_error(function_name=function_name, exception_detail=exception_detail)
@handler.add(MessageEvent, message=TextMessage)
def message_text(event):
""" Function to handle event that is a text message """
global token, original_text, text, jessin_userid, user, tag_notifier_on, api_ai_response
# Make sure user information is available
OtherUtil.get_user_info_backup(event)
# Dev / your user id
jessin_userid = "U77035fb1a3a4a460be5631c408526d0b"
# Get general information from event
original_text = event.message.text
text = original_text.lower()
token = event.reply_token
get_receiver_addr(event)
update_user_list(event)
if MEGUMI_ONLINE:
# If the text contain calling
if any(word in text for word in Lines.megumi()):
# Enable direct pass to rules mode
# megumi_bot_mode = "bot" in text[:5]
# Try to use rules type action-mapping
megumi_action = OtherUtil.function_rules_based_mapping()
# OtherUtil.megumi_logger(megumi_action, "Rules")
print("ACTION :", megumi_action, "BY RULES")
# Send the input text to API.AI for further natural language processing
if megumi_action == "Function_false":
api_ai_response = OtherUtil.api_ai(api_ai_access_token, text)
try:
megumi_action = api_ai_response["result"]["action"]
print("ACTION :", megumi_action)
except:
megumi_action = "Function_false"
# OtherUtil.megumi_logger(megumi_action, "AIAPI")
# If API.AI failed again, try to check whether it's a default chat type input by sending to megumi II
if megumi_action == "Function_false":
api_ai_response = OtherUtil.api_ai(api_ai_access_token_megumi_II, text)
try:
megumi_action = api_ai_response["result"]["action"]
print("ACTION :", megumi_action, "BY MEGUMI II")
except:
megumi_action = "Function_false"
# List of command available by sending text message
if megumi_action == "Function_random_integer" : Function.rand_int()
elif megumi_action == "Function_choose_one" : Function.choose_one_simple()
elif megumi_action == "Function_date_time" : Function.time_date()
elif megumi_action == "Function_weather_forecast" : Function.weather_forecast()
elif megumi_action == "Function_show_cinema_schedule" : Function.show_cinema_movie_schedule()
elif megumi_action == "Function_anime_download_link" : Function.anime_download_link()
elif megumi_action == "Function_summoners_war_wiki" : Function.summonerswar_wiki()
elif megumi_action == "Function_itb_arc_database" : Function.itb_arc_database()
elif megumi_action == "Function_translate" : Function.translate_text()
elif megumi_action == "Function_wiki_search" : Function.wiki_search()
elif megumi_action == "Function_show_manual" : Function.show_manual()
elif megumi_action == "Function_download_youtube" : Function.download_youtube()
elif megumi_action == "Function_echo" : Function.echo()
elif megumi_action == "Function_send_invite" : Function.send_invite()
elif megumi_action == "Function_report_bug" : Function.report_bug()
elif megumi_action == "Function_leave" : Function.leave(event)
elif megumi_action == "Function_stalk_instagram" : Function.stalk_instagram()
elif megumi_action == "Function_play_music" : Function.play_music()
elif megumi_action == "Function_hoax_analyser" : Function.hoax_or_fact()
elif megumi_action == "Enable_dev_mode" : Function.dev_authority_check()
elif megumi_action == "Dev_mode_print_userlist" :
if Function.dev_authority_check() : Function.dev_print_userlist()
elif megumi_action == "Dev_mode_set_tag_notifier" :
if Function.dev_authority_check() : Function.dev_mode_set_tag_notifier()
elif megumi_action == "Dev_mode_print_logger" :
if Function.dev_authority_check() : Function.dev_print_megumi_logger()
elif megumi_action == "Function_false" : Function.false()
else : Function.send_default_reply()
# If megumi's in partial offline mode ( for temp development )
else:
report = Lines.general_lines("offline")
line_bot_api.push_message(address, TextSendMessage(text=report))
# Special tag / mention function
if tag_notifier_on:
Function.tag_notifier()
# @handler.add(MessageEvent, message=StickerMessage)
# what does people do when being sent a sticker ???
"""
def handle_sticker_message(event):
global token
token = event.reply_token
get_receiver_addr(event)
try :
package_id = str(event.message.package_id)
sticker_id = str(event.message.sticker_id)
reply = ("package =",package_id,"\nsticker id =",sticker_id)
line_bot_api.reply_message(token,TextSendMessage(reply))
except LineBotApiError as e:
print(event.message)
print(e.status_code)
print(e.error.message)
print(e.error.details)
"""
# @handler.add(MessageEvent, message=(ImageMessage, VideoMessage, AudioMessage))
# what does people do when being sent a image, video, or audio ??? #
"""
def handle_content_message(event):
global token
token = event.reply_token
get_receiver_addr(event)
"""
@handler.add(PostbackEvent)
def handle_postback(event):
""" Function to handle event that is a postback message (send by template message) """
global token, original_text, text, jessin_userid, user, tag_notifier_on
# Make sure user information is available
OtherUtil.get_user_info_backup(event)
# Dev / your user id
jessin_userid = "U77035fb1a3a4a460be5631c408526d0b"
# Get general information from event
original_text = event.postback.data
text = original_text.lower()
token = event.reply_token
get_receiver_addr(event)
update_user_list(event)
# List of command that is available for postback event
if MEGUMI_ONLINE:
if original_text == 'ping':
line_bot_api.reply_message(token, TextSendMessage(text='pong'))
elif all(word in text for word in ["confirmation invitation"]):
if all(word in text for word in ['confirmation invitation : yes']) : Function.invite_respond("yes")
elif all(word in text for word in ['confirmation invitation : no']) : Function.invite_respond("no")
elif all(word in text for word in ['confirmation invitation : pending']) : Function.invite_respond("pending")
elif all(word in text for word in ["request", "cinema list please"]) :
if all(word in text for word in ["xxi"]) : Function.show_cinema_list("xxi")
elif all(word in text for word in ["cgv"]) : Function.show_cinema_list("cgv")
elif all(word in text for word in ["summoners_war_wiki"]) :
if all(word in text for word in ["overview"]) : Function.summonerswar_wiki("overview")
elif all(word in text for word in ["ratings"]) : Function.summonerswar_wiki("show ratings")
elif all(word in text for word in ["stats"]) : Function.summonerswar_wiki("show stats")
elif all(word in text for word in ["skills"]) : Function.summonerswar_wiki("show skills")
elif all(word in text for word in ["show megumi manual"]) : Function.show_manual()
elif all(word in text for word in ["manual : "]) : Function.show_manual("postback")
elif all(word in text for word in ["megumi dev mode print userlist"]) :
if Function.dev_authority_check() :
if all(word in text for word in ["print", "userlist"]) : Function.dev_print_userlist()
else : Function.false()
# If megumi's in partial offline mode ( for temp development )
else:
report = Lines.general_lines("offline")
line_bot_api.push_message(address, TextSendMessage(text=report))
@handler.add(JoinEvent)
def handle_join(event):
""" Function to handle join event (when bot join a chat room / group) """
global token, jessin_userid
# Make sure user information is available
OtherUtil.get_user_info_backup(event)
# Dev / your user id
jessin_userid = "U77035fb1a3a4a460be5631c408526d0b"
token = event.reply_token
get_receiver_addr(event)
# Special function dedicated for join event
Function.join()
@handler.add(FollowEvent)
def handle_follow(event):
""" Function to handle follow event (when someone add this bot) """
global token, jessin_userid
# Make sure user information is available
OtherUtil.get_user_info_backup(event)
# Dev / your user id
jessin_userid = "U77035fb1a3a4a460be5631c408526d0b"
update_user_list(event)
token = event.reply_token
# Special function dedicated for follow event
Function.added()
@handler.add(UnfollowEvent)
def handle_unfollow(event):
""" Function to handle follow event (when someone block this bot) """
global jessin_userid
# Make sure user information is available
OtherUtil.get_user_info_backup(event)
# Dev / your user id
jessin_userid = "U77035fb1a3a4a460be5631c408526d0b"
update_user_list(event)
# Special function dedicated for unfollow event
Function.removed()
""""===================================== Usable Function List ==================================================="""
class Function:
"""====================== Main Function List ==========================="""
@staticmethod
def rand_int():
""" Function to return random integer between the minimum and maximum number given in text.
Usage example : meg, pick one num from 1 to 11 """
try:
def random_number(min_number=1, max_number=5):
""" Function to generate random integer from min to max.
min set to 1 and max set to 5 by default. """
# If min and max are wrongly put, swap them
if min_number > max_number:
temp = min_number
min_number = max_number
max_number = temp
# Sampling random for more random result
a = random.randrange(min_number, max_number+1)
b = random.randrange(min_number, max_number+1)
c = random.randrange(min_number, max_number+1)
d = random.randrange(min_number, max_number+1)
e = random.randrange(min_number, max_number+1)
return random.choice([a, b, c, d, e])
def get_number():
""" Function to extract number from text """
found = []
# Iterate for each word, check weather it's a integer or not
for word in split_text:
try:
found.append(int(word))
except ValueError:
continue
return found
split_text = text.split(" ")
found_num = get_number()
report = []
# If the number is exactly 2 (min and max)
if len(found_num) == 2:
result = random_number(found_num[0], found_num[1])
report.append(Lines.rand_int("success") % str(result))
# If the number is incomplete to serve as min and max, use default settings
elif len(found_num) < 2:
result = random_number()
report.append(Lines.rand_int("default"))
report.append(Lines.rand_int("success") % str(result))
# If there are too much number or other error happened
else:
report.append(Lines.rand_int("failed"))
# Send the result to the user
report = "\n".join(report)
line_bot_api.push_message(address, TextSendMessage(text=report))
except Exception as exception_detail:
function_name = "random integer"
OtherUtil.random_error(function_name=function_name, exception_detail=exception_detail)
@staticmethod
def echo():
""" Function to echo whatever surrounded by single apostrophe (').
Usage example : Meg, try to say 'I love you <3' """
try:
# Find the index of apostrophe
index_start = text.find("'") + 1
index_stop = text.rfind("'")
# Determine whether 2 apostrophe are exist and the text exist
text_to_echo_available = (index_stop - index_start) >= 1
# If there are at least 2 apostrophes found and the text (which should be echo-ed) is found as well
if text_to_echo_available:
echo_text = text[index_start:index_stop]
report = Lines.echo("success") % echo_text
# If the text is not found
else:
report = Lines.echo("failed")
# Send the result
line_bot_api.push_message(address, TextSendMessage(text=report))
except Exception as exception_detail:
function_name = "echo"
OtherUtil.random_error(function_name=function_name, exception_detail=exception_detail)
@staticmethod
def choose_one_simple():
""" Function to return one random item from listed items.
Usage example : Meg, choose one between #pasta and #pizza """
try:
def get_options(tag):
""" Function to return a list of found options """
found = []
split_text = text.split(" ")
for word in split_text:
# If the word contain the item tag
if tag in word:
word = word.replace(tag, "")
is_word_valid = (word is not None) and (word != "")
# If the word is not None and not empty
if is_word_valid:
found.append(word)
return found
item_tag = '#'
found_options = get_options(item_tag)
# If the option(s) is/are available
if len(found_options) > 0:
result = random.choice(found_options)
report = Lines.choose_one("success") % str(result)
# Else if the options is not valid or not available
else:
report = Lines.choose_one("fail")
line_bot_api.push_message(address, TextSendMessage(text=report))
except Exception as exception_detail:
function_name = "Choose one"
OtherUtil.random_error(function_name=function_name, exception_detail=exception_detail)
@staticmethod
def time_date():
""" Function to get the time and date from server.
Usage example : Meg, what time is it in gmt +4 ?? """
try:
def find_gmt(default_gmt):
""" Function to return specific gmt if listed in text """
keyword = ['', ' ', '?', 'about', 'are', 'at', 'be', 'do', 'does', 'for', 'gonna', 'have',
'how', "how's", 'in', 'information', 'is', 'it', 'kato', 'kato,', 'like', 'me',
'meg', 'meg,', 'megumi', 'megumi,', 'now', 'please', 'pls', 'show', 'the', 'think',
'this', 'to', 'what', "what's", 'whats', 'will', 'you'
]
filtered_text = OtherUtil.filter_words(text, cond="date and time")
filtered_text = OtherUtil.filter_keywords(filtered_text, keyword)
# Initial state for timezone
timezone = default_gmt
keyword = ["gmt"]
# Search for number which follow 'gmt' in text
for i in range(0, len(filtered_text)):
# If the keyword is found
if any(word in filtered_text[i] for word in keyword):
try:
timezone = int(filtered_text[i + 1])
return timezone
except Exception:
# When user said 'time in gmt' it means gmt +0
timezone = 0
return timezone
def valid_gmt(gmt):
""" Return boolean whether the GMT is valid or not """
if (gmt > 12) or (gmt < (-12)):
return False
else:
return True
def ordinal(n):
""" Function to return an ordinal style of a number """
return str("%d%s" % (n, "tsnrhtdd"[(math.floor(n / 10) % 10 != 1) * (n % 10 < 4) * n % 10::4]))
def convert_am_pm(hh):
""" Function to change 24 hours format into 12 hours format with Am or Pm """
am_pm = "am"
if int(hh) > 12:
hh = int(hh)
hh -= 12
hh = str(hh)
am_pm = "pm"
return hh, am_pm
# General variable
default_gmt = 7
report = ""
cont = True
gmt_timezone = find_gmt(default_gmt)
is_gmt_valid = valid_gmt(gmt_timezone)
# Happen when gmt is not valid
if not is_gmt_valid:
report = "I think the timezone is a little bit off... should be between -12 to 12 isn't ??"
cont = False
# If the GMT is valid, format the data
if cont:
split_time = time.ctime(time.time() + gmt_timezone * 3600).split(" ")
# If there's unwanted element in the list
if ('' in split_time) or (None in split_time):
# Remove the unwanted element
for element in split_time:
if (element == '') or (element is None):
split_time.remove(element)
try:
# Gather the date and time data into several variable
splitted_hour = split_time[3].split(":")
day = Lines.day()[split_time[0]]
MM = Lines.month()[split_time[1].lower()]
DD = split_time[2]
YYYY = split_time[4]
hh = splitted_hour[0]
mm = splitted_hour[1]
except:
report = Lines.date_time("formatting error")
cont = False
# If the data formatting success, send the result
if cont:
# If user ask for date / day
if any(word in text for word in ["date", "day"]):
report = Lines.date_time("show date").format(day, DD, ordinal(int(DD)), MM, YYYY)
# Else if user ask for time
elif "time" in text:
hh, AmPm = convert_am_pm(hh)
report = Lines.date_time("show time").format(hh, mm, AmPm)
line_bot_api.push_message(address, TextSendMessage(text=report))
except Exception as exception_detail:
function_name = "Time and Date"
OtherUtil.random_error(function_name=function_name, exception_detail=exception_detail)
@staticmethod
def send_invite():
""" Function to send button template as invitation. Detail and participant list is given in text.
Usage example : meg, can you send invite 'Go to the beach' to close-friend ? """
try:
global invitation_sender, invitation_sender_id
def get_invitation_data():
""" Function to find the description of invitation from text """
# Find the index of apostrophe
index_start = text.find("'")+1
index_stop = text.rfind("'")
# Determine whether 2 apostrophe are exist and the text exist
text_available = (index_stop - index_start) >= 1
if text_available:
invite_desc = text[index_start:index_stop]
no_invite_desc = False
else:
invite_desc = " (つ≧▽≦)つ "
no_invite_desc = True
return invite_desc, no_invite_desc
def get_participant_list():
""" Function to find participant list from text """
try:
# Get the participant list name
filtered_text = OtherUtil.filter_words(text)
invite_list_index = filtered_text.index("to") + 1
list_name = filtered_text[invite_list_index]
# Try to find the list from database
invite_list = Database.list_dictionary[list_name]
no_invite_list = False
# If the list is not listed in database, or the list name is unavailable
except Exception:
invite_list = Database.list_dictionary["dev"]
no_invite_list = True
return invite_list, no_invite_list
# General variable
cont = True
report = []
desc, no_desc = get_invitation_data()
invite_list, no_invite_list = get_participant_list()
# If there is missing element, send special notification
if no_desc or no_invite_list:
if no_desc:
report.append(Lines.invite_report("desc missing"))
cont = True
if no_invite_list:
report.append(Lines.invite_report("participant list missing"))
cont = False
report = "\n".join(report)
line_bot_api.push_message(address, TextSendMessage(text=report))
# If the participant list is valid, create the invitation
if cont:
# Default variable for template message
header_pic = Picture.header("background")
title = 'Invitation'
# Get the sender information
invitation_sender_id = user_id
invitation_sender = user_name
# Generate the invitation
buttons_template = ButtonsTemplate(title=title, text=desc, thumbnail_image_url=header_pic, actions=[
PostbackTemplateAction(label='Count me in', data='confirmation invitation : yes'),
PostbackTemplateAction(label='No thanks', data='confirmation invitation : no'),
PostbackTemplateAction(label='Decide later', data='confirmation invitation : pending')
])
template_message = TemplateSendMessage(alt_text=desc, template=buttons_template)
# Sending the invitation
try:
report = Lines.invite("header") % invitation_sender
invitation_sent = 0
# Send the invitation to user listed in the participant list
for participant in invite_list:
line_bot_api.push_message(participant, TextSendMessage(text=report))
line_bot_api.push_message(participant, template_message)
invitation_sent += 1
# If the invitation request is sent via personal chat, send confirmation of invitations sent
if invitation_sender != "someone":
report = Lines.invite("success") % (str(invitation_sent))
line_bot_api.push_message(invitation_sender_id, TextSendMessage(text=report))
# If there's unexpected error while sending the invite
except Exception:
# If the sender is known, send 'failed' notification to the sender
if invitation_sender != "someone":
report = Lines.invite("failed")
line_bot_api.push_message(invitation_sender_id, TextSendMessage(text=report))
raise
except Exception as exception_detail:
function_name = "Send Invite"
OtherUtil.random_error(function_name=function_name, exception_detail=exception_detail)
@staticmethod
def invite_respond(cond):
""" Function to notice the invitation sender about the response from participants.
Usage example: (none : passive function) """
try:
global invitation_sender
# Check whether invitation sender is available, if not set invitation sender as 'someone'
try:
sender_known = (invitation_sender != "someone") and (invitation_sender is not None)
except:
sender_known = False
# Get the responder data
responder_id = user_id
responder = user_name
# Send report to responder if their respond is recorded
report = Lines.invite_report("respond recorded")
line_bot_api.push_message(responder_id, TextSendMessage(text=report))
# Send report to sender about the response
try:
report = Lines.invite_report(cond) % responder
# If the sender is known, send the report
if sender_known:
line_bot_api.push_message(invitation_sender_id, TextSendMessage(text=report))
# If the sender is unknown / group / room, send the report to default userid instead
else:
line_bot_api.push_message(jessin_userid, TextSendMessage(text=report))
# If there's unexpected error
except Exception:
raise
except Exception as exception_detail:
function_name = "Invite respond"
OtherUtil.random_error(function_name=function_name, exception_detail=exception_detail)
@staticmethod
def show_cinema_movie_schedule():
""" Function to show list of movies playing at certain cinemas.
Usage example : Meg, can you show me citylink xxi movie schedule ? """
try:
cont = True
# If the cinema is not specified, send notification, stop process
if not(any(word in text for word in ["xxi", "cgv"])):
report = Lines.show_cinema_movie_schedule("specify the company")
line_bot_api.push_message(address, TextSendMessage(text=report))
cont = False
# If the cinema is specified either xxi or cgv
if cont:
# The cinema is one of the XXI cinemas
if "xxi" in text:
# TEMPORARY ERROR NOTICE
report = Lines.show_cinema_movie_schedule("failed to open the the page")+"\n\n\nDev note: can't reach xxi web server (code 0X170925)"
line_bot_api.push_message(address, TextSendMessage(text=report))
'''
def get_cinema_keyword():
""" Function to get cinema's name keyword from text """
keyword = ['are', 'at', 'can', 'film', 'help', 'is', 'kato', 'list', 'me', 'meg', 'megumi',
'movie', 'movies', 'playing', 'please', 'pls', 'schedule', 'show',
'showing', 'you', 'xxi', 'what']
search_keyword = OtherUtil.filter_words(text)
search_keyword = OtherUtil.filter_keywords(search_keyword, keyword)
return search_keyword
def get_cinema_list(search_keyword):
""" Function to return available cinema list """
cinemas = []
page_url = "http://www.21cineplex.com/theaters"
# Open the XXI page
try:
proxy = random.choice(proxies)
req = requests.get(page_url,headers={'User-Agent': "Magic Browser"})
page_source_code_text = req.content
mod_page = BeautifulSoup(page_source_code_text, "html.parser")
# Failed to open the XXI page
except Exception:
report = Lines.show_cinema_movie_schedule("failed to open the the page")
line_bot_api.push_message(address, TextSendMessage(text=report))
raise
# Get the cinema's link that fulfil the keyword
links = mod_page.findAll('a')
for link in links:
cinema_link = link.get("href")
if all(word in cinema_link for word in
(["http://www.21cineplex.com/theater/bioskop"] + search_keyword)):
cinemas.append(cinema_link)
# Just in case there are duplicate link, remove the duplicates
if len(cinemas) > 1:
cinemas = set(cinemas)
return cinemas
def get_movie_data(cinema):
""" Function to return the movie's data, in form of (movie, description, schedule) """
# Default variable
movielist = []
desclist = []
schedulelist = []
# Open the page to parse
try:
proxy = random.choice(proxies)
req = requests.get(cinema,headers={'User-Agent': "Magic Browser"})
page_source_code_text = req.content
mod_page = BeautifulSoup(page_source_code_text, "html.parser")
mod_schedule_table = BeautifulSoup(
str(mod_page.find("table", {"class": "table-theater-det"})), "html.parser")
# If failed to open the page
except Exception:
report = Lines.show_cinema_movie_schedule("failed to open the the page")
line_bot_api.push_message(address, TextSendMessage(text=report))
raise
# Finding all movie's title, description, and showtime
try:
# Get the movie's title and description
movies = mod_schedule_table.findAll('a')
for movie in movies:
# Get the title
title = movie.string
if title is not None:
movielist.append(title)
# Get the description (nb: put here to limit number of desc <= number of title)
movie_description = movie.get("href")
# If the description is already existed before, don't append it again
if movie_description in desclist:
desclist.append(" ")
else:
desclist.append(movie_description)
# Get movie's showtime
showtimes = mod_schedule_table.findAll("td", {"align": "right"})
for showtime in showtimes:
schedulelist.append(showtime.string)
except Exception:
report = Lines.show_cinema_movie_schedule("failed to get movie data")
line_bot_api.push_message(jessin_userid, TextSendMessage(text=report))
raise
moviedata = zip(movielist, desclist, schedulelist)
return moviedata
def get_cinema_name(cinema_link):
""" Function to get cinema name """
# Get the cinema name
index_start = cinema_link.find("-") + 1
index_end = cinema_link.find(",")
cinema_name = cinema_link[index_start:index_end]
cinema_name = cinema_name.replace("-", " ")
# Special case TSM
if cinema_name == "tsm xxi":
if cinema_link == "http://www.21cineplex.com/theater/bioskop-tsm-xxi,186,BDGBSM.htm":
cinema_name = "tsm xxi (Bandung)"
elif cinema_link == "http://www.21cineplex.com/theater/bioskop-tsm-xxi,335,UPGTSM.htm":
cinema_name = "tsm xxi (Makassar)"
return cinema_name
def request_cinema_list():
""" Function to send confirmation whether send request cinema list or not """
# Generate button template
confirmation = Lines.show_cinema_movie_schedule("asking to show cinema list")
buttons_template = ButtonsTemplate(text=confirmation, actions=[
PostbackTemplateAction(label="Sure...", data='request xxi cinema list please',
text='Sure...')])
template_message = TemplateSendMessage(alt_text=confirmation, template=buttons_template)
# Send the template
line_bot_api.push_message(address, template_message)
def send_header(search_keyword):
""" Function to send header to user as his/her request is accepted """
report = Lines.show_cinema_movie_schedule("header") % (" ".join(search_keyword))
line_bot_api.push_message(address, TextSendMessage(text=report))
search_keyword = get_cinema_keyword()
# If the cinema keyword is unspecified
if search_keyword == [] or search_keyword == [""]:
report = Lines.show_cinema_movie_schedule("No keyword found")
line_bot_api.push_message(address, TextSendMessage(text=report))
ask_for_request = True
# If keyword is found
else:
# Request accepted confirmation
send_header(search_keyword)
cinemas = get_cinema_list(search_keyword)
# Process the cinemas found
if len(cinemas) <= 0:
report = Lines.show_cinema_movie_schedule("No cinema found") % (", ".join(search_keyword))
ask_for_request = True
elif len(cinemas) > 2:
report = Lines.show_cinema_movie_schedule("Too many cinemas") % (", ".join(search_keyword))
ask_for_request = True