-
Notifications
You must be signed in to change notification settings - Fork 0
/
interactions.py
885 lines (724 loc) · 36.7 KB
/
interactions.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
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
import random, requests, json, datetime
import pandas as pd
from tools import *
weather_api_key = 'F7DxhfQx1EoPuopgN59Tq0OkGRJwVkWQ'
class bordem_entertainment():
def play_game():
print(chatbot_tools.random_output('play which game'))
def play_video():
from youtubesearchpython import VideosSearch
import webbrowser
user_video = input(chatbot_tools.random_output('which video') + '\n>>> ')
videoResults = VideosSearch(user_video, limit=1)
webbrowser.open(videoResults.result()['result'][0]['link'])
class games():
def rps():
user_data = chatbot_tools.get_user_data()
bot_answer = random.choice(['Rock', 'Paper', 'Scissors'])
user_answer = input('You can just say R for rock, P for paper, and S for scissors. Ready... Rock... Paper... Scissors... Shoot.')
print("Bot answer: ", bot_answer)
print("user answer: ", user_answer)
print("bot letter: ", (bot_answer)[0].lower())
while user_answer.lower() not in ['rock', 'paper', 'scissors', 'r', 'p', 's']:
pass #invalid input
if user_answer.lower() == bot_answer or user_answer.lower() == list(bot_answer)[0].lower():
print(chatbot_tools.random_output('rps tie'))
elif (
(user_answer.lower() == 'rock' and bot_answer == 'scissors' or user_answer.lower() == 'r' and bot_answer == 'scissors') or
(user_answer.lower() == 'paper' and bot_answer == 'rock' or user_answer.lower() == 'p' and bot_answer == 'rock') or
(user_answer.lower() == 'scissors' and bot_answer == 'paper' or user_answer.lower() == 's' and bot_answer == 'paper')
):
print('I chose ' + bot_answer)
print(chatbot_tools.random_output('rps win').replace('<user-name>', user_data['first name']))
else:
print('I chose ' + bot_answer)
print(chatbot_tools.random_output('rps lose').replace('<user-name>',user_data['first name']))
def numberGuess():
user_data = chatbot_tools.get_user_data()
random_number = random.randint(1, 100)
print('Okay I have my number.')
run_game = True
while run_game is True:
user_guess = int(input('Now take a guess. Any number between 1 and 100.'))
if user_guess > random_number and user_guess < 100:
print('Too high. Try again.')
elif user_guess < random_number and user_guess > 0:
print('Too low. Try again.')
elif user_guess < 0:
print(chatbot_tools.random_output('number too low'))
elif user_guess > 100:
print(chatbot_tools.random_output('number to high'))
elif user_guess == random_number:
print(chatbot_tools.random_output('guess number win').replace('<user-name>', user_data['first name']))
run_game = False
else:
print(chatbot_tools.random_output('incorrect number guess'))
def blackjack(user_input):
def create_deck():
deck = []
for suit in suits:
for rank in ranks:
deck.append((rank, suit))
return deck
def deal_card(deck, hand):
card = deck.pop()
hand.append(card)
def calculate_hand_value(hand):
value = 0
num_aces = 0
for card in hand:
rank = card[0]
value += values[rank]
if rank == 'Ace':
num_aces += 1
while value > 21 and num_aces:
value -= 10
num_aces -= 1
return value
user_data = chatbot_tools.get_user_data()
user_game_name = 'blackjack'
if 'blackjack' in user_input.lower():
user_game_name = 'blackjack'
elif 'twenty one' in user_input.lower() or '21' in user_input.lower():
user_game_name = 'twenty one'
elif 'pontoon' in user_input.lower():
user_game_name = 'pontoon'
print(chatbot_tools.random_output('welcome blackjack game').replace('<game-name>', user_game_name))
# Define card ranks, suits, and values
suits = ('Hearts', 'Diamonds', 'Clubs', 'Spades')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10,
'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11}
deck = create_deck()
random.shuffle(deck)
player_hand = []
dealer_hand = []
for _ in range(2):
deal_card(deck, player_hand)
deal_card(deck, dealer_hand)
while True:
print("\nYour Hand:")
for card in player_hand:
print(f"{card[0]} of {card[1]}")
player_value = calculate_hand_value(player_hand)
print(f"Total Value: {player_value}")
if player_value == 21:
print("Blackjack!")
print(chatbot_tools.random_output('user win blackjack').replace('<user-name>', user_data['first name']))
break
elif player_value > 21:
print("Bust!")
print(chatbot_tools.random_output('dealer win blackjack').replace('<user-name>', user_data['first name']))
break
action = input("Do you want to 'hit' or 'stand'? ").lower()
if 'hit' in action or action == 'h':
deal_card(deck, player_hand)
elif 'stand' in action or action == 's':
while calculate_hand_value(dealer_hand) < 17:
deal_card(deck, dealer_hand)
print("\nDealer's Hand:")
for card in dealer_hand:
print(f"{card[0]} of {card[1]}")
dealer_value = calculate_hand_value(dealer_hand)
print(f"Total Value: {dealer_value}")
if dealer_value > 21:
print("Dealer busts!")
print(chatbot_tools.random_output('user win blackjack').replace('<user-name>', user_data['first name']))
elif dealer_value >= player_value:
print(chatbot_tools.random_output('dealer win blackjack').replace('<user-name>', user_data['first name']))
else:
print(chatbot_tools.random_output('user win blackjack').replace('<user-name>', user_data['first name']))
break
print(chatbot_tools.random_output('play blackjack again'))
def open_wiki_game():
import webbrowser
webbrowser.open('https://www.thewikigame.com/group')
def xkcd():
import webbrowser
number = random.randint(0, 2801)
webbrowser.open(f"https://xkcd.com/{number}/")
def akinator():
import webbrowser
webbrowser.open('https://en.akinator.com/theme-selection')
def game_list():
games = '\n'.join(['blackjack','number guess','wiki game','akinator'])
print(chatbot_tools.random_output('list playable games').replace('<list-games>', games))
def tell_joke():
jokes_data = pd.read_csv('data/datasets/jokes.csv')
random_joke = jokes_data.iloc[random.randint(0, len(jokes_data))]
setup_joke = random_joke['setup']
punchline = random_joke['punchline']
for column, value in random_joke.items():
if not pd.isna(punchline):
print(setup_joke)
print(punchline)
break
else:
print(setup_joke)
break
def tell_riddle():
user_data = chatbot_tools.get_user_data()
riddles_data = pd.read_csv('data/datasets/riddles.csv')
random_riddle = riddles_data.iloc[random.randint(0, len(riddles_data))]
riddle_question = random_riddle['question']
riddle_answer = random_riddle['answer']
user_answer = input(riddle_question + '\n>>> ').lower()
if riddle_answer in user_answer:
print(chatbot_tools.random_output('correct riddle').replace('<user-name>', user_data['first name']).replace('<riddle-answer>', riddle_answer))
else:
print(chatbot_tools.random_output('incorrect riddle').replace('<user-name>', user_data['first name']).replace('<riddle-answer>', riddle_answer))
def trivia_quiz(number_of_questions):
import html
#create a dictionary of all the questions ranking from easy to hard
questions_by_difficulty = {'easy': [], 'medium': [], 'hard': []}
#write the number of questions to a file
with open('data/amountOfQuestions.txt', 'w') as f:
f.write(str(number_of_questions))
#open the json file of questions and answers
with open('data/datasets/trivia.json', 'r') as f:
trivia_questions = json.load(f)
for q in trivia_questions:
questions_by_difficulty[q['difficulty']].append(q)
#what difficulty the user wants the questions to be.
with open('data/quiz difficulty.txt', 'r') as f:
read = f.read()
if read == 'none':
amount_of_questions = len(trivia_questions)
random_number = random.randint(0, amount_of_questions)
question = html.unescape(trivia_questions[random_number]['question'])
correct_answer = html.unescape(trivia_questions[random_number]['correct_answer'])
incorrect_answers = html.unescape(trivia_questions[random_number]['incorrect_answers']) #this is used to get a list of either one or three incorrect answers.
answers = incorrect_answers + [correct_answer]
with open('data/expected context.txt', 'w') as f:
f.write('waiting trivia answer\n' + correct_answer)
print(question)
random.shuffle(answers)
i = 1
for a in answers:
print(f"{i}) {answers[i-1]}")
i += 1
else:
#random question
question_data = random.choice(questions_by_difficulty[read])
#question info
question = html.unescape(question_data['question'])
correct_answer = html.unescape(question_data['correct_answer'])
incorrect_answers = html.unescape(question_data['incorrect_answers'])
answers = incorrect_answers + [correct_answer]
with open('data/expected context.txt', 'w') as f:
f.write('waiting trivia answer\n' + correct_answer)
#output question and possible answers.
print(question)
random.shuffle(answers)
i = 1
for a in answers:
print(f"{i}) {answers[i-1]}")
i += 1
def facts():
with open('data/datasets/facts.txt', 'r') as f:
read = f.read().splitlines()
print(chatbot_tools.random_output('give fact'))
print(random.choice(read))
def wikihow():
print(chatbot_tools.random_output('wikihow random'))
def factory_reset():
files_to_empty = ['expected context.txt', 'last time used.txt', 'log.txt', 'quiz difficulty.txt', 'user passcode.txt', 'wiki links.txt']
#make sure all txt data files are emptied
for file in files_to_empty:
with open('data/' + file, 'w') as f:
f.write('')
#forgetting user data
with open('data/user data.csv', 'r', newline='') as file:
csv_reader = csv.reader(file)
data = list(csv_reader)
# Clear the data in the 2nd row (except the first column)
if len(data) > 1:
data[1][1:] = [''] * (len(data[1]) - 1)
# Write the modified content back to the same CSV file
with open('data/user data.csv', 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(data)
#reset Joan, it should think that the user is new
with open('data/new user.txt', 'w') as f:
f.write('true')
#restarts the python script
chatbot_tools.restart_program()
def current_weather():
user_data = chatbot_tools.get_user_data()
internet = check_internet()
if internet == 0:
location_key = user_data['location key']
url = f"http://dataservice.accuweather.com/currentconditions/v1/{location_key}?apikey={weather_api_key}&details=true"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
current_weather = data[0]['WeatherText']
current_temperature = str(data[0]['Temperature']['Metric']['Value'])
print(f"The current weather in {user_data['city']} is {current_weather} and the temperature is {current_temperature} celsius")
else:
print(chatbot_tools.random_output('unaccessable weather').replace('<user-name>', user_data['first name']))
else:
print(chatbot_tools.random_output('no internet').replace('<user-name>', user_data['first name']))
def weather_tomorrow():
internet = check_internet()
if internet == 0:
user_data = chatbot_tools.get_user_data()
location_key = user_data['location key']
url = f"http://dataservice.accuweather.com/forecasts/v1/daily/1day/{location_key}"
params = {
'apikey': weather_api_key,
'metric': True, # Use metric units for temperature
'details': True # Request additional details in the forecast
}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
tomorrow_weather = data['DailyForecasts'][0]['Day']['LongPhrase']
percentageOfRain = data['DailyForecasts'][0]['Day']['PrecipitationProbability']
precentageOfThunder = data['DailyForecasts'][0]['Day']['ThunderstormProbability']
percentageOfSnow = data['DailyForecasts'][0]['Day']['SnowProbability']
hoursOfRain = data['DailyForecasts'][0]['Day']['HoursOfRain']
grassPollon = data['DailyForecasts'][0]['AirAndPollen'][1]['Category']
moldPollon = data['DailyForecasts'][0]['AirAndPollen'][2]['Category']
treePollon = data['DailyForecasts'][0]['AirAndPollen'][3]['Category']
minimum_temperature = data['DailyForecasts'][0]['Temperature']['Minimum']['Value']
maximum_temperature = data['DailyForecasts'][0]['Temperature']['Maximum']['Value']
print(f"For {user_data['city']}, {tomorrow_weather}. Chance to rain: {str(percentageOfRain)}%. This rain should last about {str(hoursOfRain)} hours. The chance for a thunder storm is {str(precentageOfThunder)}% and the chance for snow is {str(percentageOfSnow)}%")
print(f"Grass pollon is {grassPollon}. Mold pollon is {moldPollon}, and tree pollon is {treePollon}")
print(f"The minimum temperature for tomorrow is {str(minimum_temperature)} celsius, and the maximum temperature for tomorrow is {str(maximum_temperature)} celsius")
else:
print(chatbot_tools.random_output('unaccessable weather').replace('<user-name>', user_data['first name']))
else:
print(chatbot_tools.random_output('no internet').replace('<user-name>', user_data['first name']))
def weather_for_area(place):
user_data = chatbot_tools.get_user_data()
internet = check_internet()
location_key = ''
if internet == 0:
weather_api_key = 'F7DxhfQx1EoPuopgN59Tq0OkGRJwVkWQ'
# AccuWeather API endpoint for location search
url = f"http://dataservice.accuweather.com/locations/v1/cities/search"
# Parameters for the API request
params = {
'apikey': weather_api_key,
'q': place,
}
# Make the API request
response = requests.get(url, params=params)
# Check if the request was successful
if response.status_code == 200:
data = response.json()
# Assuming you want the first result
if data:
location_key = data[0]['Key']
# Get the weather from the location specified
url = f"http://dataservice.accuweather.com/currentconditions/v1/{location_key}?apikey={weather_api_key}&details=true"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
current_weather = data[0]['WeatherText']
current_temperature = str(data[0]['Temperature']['Metric']['Value'])
print(f"The current weather in {place} is {current_weather} and the temperature is {current_temperature} celsius")
else:
print(chatbot_tools.random_output('unaccessable weather').replace('<user-name>', user_data['first name']))
else:
print(chatbot_tools.random_output('no internet').replace('<user-name>', user_data['first name']))
def weather_day(day):
user_data = chatbot_tools.get_user_data()
internet = check_internet()
if internet == 0:
date = chatbot_tools.day_to_date(day.title())
url = f"https://dataservice.accuweather.com/forecasts/v1/daily/1day/{user_data['location key']}?apikey={weather_api_key}&details=true&date={date}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
tomorrow_weather = data['DailyForecasts'][0]['Day']['LongPhrase']
percentageOfRain = data['DailyForecasts'][0]['Day']['PrecipitationProbability']
precentageOfThunder = data['DailyForecasts'][0]['Day']['ThunderstormProbability']
percentageOfSnow = data['DailyForecasts'][0]['Day']['SnowProbability']
hoursOfRain = data['DailyForecasts'][0]['Day']['HoursOfRain']
grassPollon = data['DailyForecasts'][0]['AirAndPollen'][1]['Category']
moldPollon = data['DailyForecasts'][0]['AirAndPollen'][2]['Category']
treePollon = data['DailyForecasts'][0]['AirAndPollen'][3]['Category']
minimum_temperature = data['DailyForecasts'][0]['Temperature']['Minimum']['Value']
maximum_temperature = data['DailyForecasts'][0]['Temperature']['Maximum']['Value']
print(f"For {user_data['city']}, {tomorrow_weather}. Chance to rain: {str(percentageOfRain)}%. This rain should last about {str(hoursOfRain)} hours. The chance for a thunder storm is {str(precentageOfThunder)}% and the chance for snow is {str(percentageOfSnow)}%")
print(f"Grass pollon is {grassPollon}. Mold pollon is {moldPollon}, and tree pollon is {treePollon}")
print(f"The minimum temperature for tomorrow is {str(minimum_temperature)} celsius, and the maximum temperature for tomorrow is {str(maximum_temperature)} celsius")
else:
print(chatbot_tools.random_output('unaccessable weather').replace('<user-name>', user_data['first name']))
else:
print(chatbot_tools.random_output('no internet').replace('<user-name>', user_data['first name']))
def weather_hour_advanced():
user_data = chatbot_tools.get_user_data()
current_time = datetime.datetime.now()
rounded_time = (current_time + datetime.timedelta(hours=1)).replace(minute=0, second=0, microsecond=0)
format_time = rounded_time.strftime("%Y-%m-%dT%H:%m:%S")
url = f"https://dataservice.accuweather.com/forecasts/v1/hourly/1hour/{user_data['location key']}"
params = {
"apikey": weather_api_key,
"details": True,
"metric": True,
"startdate": format_time
}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
get_time = data[0]['DateTime'].split('T')[1].split('+')[0].split(':')
phrase = f"It will be {data[0]['PrecipitationIntensity']} {data[0]['PrecipitationType'].lower().replace('rain', 'raining')} at {get_time[0] + ':' + get_time[1]} in {user_data['city']}"
temperature = str(data[0]['Temperature']['Value']) + ' Celcius'
rain_prob = str(data[0]['RainProbability']) + '%'
snow_prob = str(data[0]['SnowProbability']) + '%'
thunder_prob = str(data[0]['ThunderstormProbability']) + '%'
print(phrase)
print(f"The temperature will be {temperature}. The chance for rain is {rain_prob}, the chance for thunder is {thunder_prob} and the chance for snow is {snow_prob}.")
def tell_time():
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%H:%M")
print(f"The current time is {formatted_time}")
def tell_date():
current_date = datetime.datetime.now()
formatted_date = current_date.strftime('%d/%m/%Y')
print(f"Today's date it {formatted_date}")
def tell_day():
current_date = datetime.datetime.today()
current_day = current_date.weekday()
days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print("It is", days_of_week[current_day], "today.")
def tell_month():
current_date = datetime.datetime.now()
current_month = current_date.strftime('%B')
print(f"The month is {current_month}")
def tell_year():
print(f"The year is {datetime.datetime.now().year}")
class movie():
def read_movie_data():
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
return data
except Exception as e:
print(e)
def collect_data(user_input, function):
movie_data = {}
user_input = (user_input.lstrip().rstrip().title())
fun = function(user_input)
if fun != '':
pass
else:
internet = check_internet()
if internet == 0:
response = requests.get(f"https://www.omdbapi.com/?apikey=32486892&s={user_input.replace(' ','%20')}")
if response.status_code == 200:
data = response.json()
#usful data elements
try:
title = data['Search'][0]['Title'].title()#TODO: This returns an error, need to deal with it
year = data['Search'][0]['Year']
ID = data['Search'][0]['imdbID']
file_type = data['Search'][0]['Type']
image_url = data['Search'][0]['Poster']
#call for addional detail using the id
url = f"https://www.omdbapi.com/?apikey=32486892&i={ID}"
detailed_response = requests.get(url)
if detailed_response.status_code == 200:
data = detailed_response.json()
rated = data['Rated']
released = data['Released']
runtime = data['Runtime']
genre = data['Genre']
director = data['Director']
writer = data['Writer']
actors = data['Actors']
plot = data['Plot']
languages = data['Language']
awards = data['Awards']
for rating in data['Ratings']:
if rating['Source'] == 'Rotten Tomatoes':
rate = rating['Value']
try:
#reads currently collected data
with open('data/datasets/movie data.json', 'r') as f:
movie_data = json.load(f)
except:
pass
#writes data to a dictionary
collected_data = {
"Year": released,
"rated": rated,
"runTime": runtime,
"genre": genre,
"director": director,
"writer": writer,
"actors": actors,
"plot": plot,
"languages": languages,
"awards": awards,
"rate": rate}
movie_data[title] = collected_data
#writes all previous and new data to file
with open('data/datasets/movie data.json', 'w') as f:
json.dump(movie_data, f, indent=4)
else:
print(response.status_code)
print(function(user_input))
except KeyError:
pass
else:
print(chatbot_tools.random_output('no internet'))
def release(user_input):
user_input = user_input.title().lstrip().rstrip().replace(' D', '')
try:
movie_data = movie.read_movie_data()
movie_data = movie_data[user_input]
return (f"{user_input} was released in {movie_data['Year']}")
except KeyError:
try:
movie_data = movie.read_movie_data()
movie_data = movie_data["The " + user_input]
print(f"The {user_input} was released in {movie_data['Year']}")
except:
chatbot_tools.big_guns(user_input)
def rate(user_input):
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data[user_input]
return(f"{user_input} is rated {movie_data['rated']}")
except KeyError:
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data["The " + user_input]
print(f"The {user_input} is rated {movie_data['rated']}")
except:
chatbot_tools.big_guns(user_input)
def runtime(user_input):
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data[user_input]
return f"{user_input} runs for {movie_data['runTime'].replace('min', 'minutes')}"
except KeyError:
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data["The " + user_input]
print(f"The {user_input} runs for {movie_data['runTime'].replace('min', 'minutes')}")
except:
chatbot_tools.big_guns(user_input)
def genre(user_input):
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data[user_input]
return f"The genre for {user_input} is {movie_data['genre']}"
except KeyError:
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data["The " + user_input]
print(f"The genre for The {user_input} is {movie_data['genre']}")
except:
chatbot_tools.big_guns(user_input)
def director(user_input):
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data[user_input]
list_of_directors = movie_data['director'].split(', ')
directors = ", ".join(list_of_directors[:-1]) + " and " + list_of_directors[-1]
return f"The directors for {user_input} are {directors}"
except KeyError:
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data["The " + user_input]
list_of_directors = movie_data['director'].split(', ')
directors = ", ".join(list_of_directors[:-1]) + " and " + list_of_directors[-1]
print(f"The directors for The {user_input} are {directors}")
except:
chatbot_tools.big_guns(user_input)
def writer(user_input):
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data[user_input]
list_of_writer = movie_data['writer'].split(', ')
writers = ", ".join(list_of_writer[:-1]) + " and " + list_of_writer[-1]
return f"The directors for {user_input} are {writers}"
except KeyError:
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data["The " + user_input]
list_of_writer = movie_data['writer'].split(', ')
writers = ", ".join(list_of_writer[:-1]) + " and " + list_of_writer[-1]
print(f"The directors for The {user_input} are {writers}")
except:
chatbot_tools.big_guns(user_input)
def actor(user_input):
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data[user_input]
list_of_actors = movie_data['actors'].split(', ')
actors = ", ".join(list_of_actors[:-1]) + " and " + list_of_actors[-1]
return f"The actors for {user_input} are {actors}"
except Exception as e:
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data["The " + user_input]
list_of_actors = movie_data['actors'].split(', ')
actors = ", ".join(list_of_actors[:-1]) + " and " + list_of_actors[-1]
print(f"The actors for The {user_input} are {actors}")
except:
chatbot_tools.big_guns(user_input)
def plot(user_input):
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data[user_input]
plot = movie_data['plot']
return f"The plot of {user_input} is: {plot}"
except KeyError:
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data["The " + user_input]
plot = movie_data['plot']
return f"The plot of The {user_input} is: {plot}"
except:
chatbot_tools.big_guns(user_input)
def languages(user_input):
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data[user_input]
list_of_languages = movie_data['languages'].split(', ')
languages = ", ".join(list_of_languages[:-1]) + " and " + list_of_languages[-1]
return f"The languages for {user_input} are {languages}"
except KeyError:
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data["The " + user_input]
list_of_languages = movie_data['languages'].split(', ')
languages = ", ".join(list_of_languages[:-1]) + " and " + list_of_languages[-1]
print(f"The languages for The {user_input} are {languages}")
except:
chatbot_tools.big_guns(user_input)
def awards(user_input):
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data[user_input]
awards = movie_data['awards']
return f"The awards for {user_input} is: {awards}"
except KeyError:
try:
with open('data/datasets/movie data.json', 'r') as f:
data = json.load(f)
movie_data = data["The " + user_input]
awards = movie_data['awards']
print(f"The awards for The {user_input} is: {awards}")
except:
chatbot_tools.big_guns(user_input)
def read_latest_news():
internet = check_internet()
if internet == 0:
print(chatbot_tools.random_output('read article'))
else:
print(chatbot_tools.random_output('no internet'))
def read_space_news():
internet = check_internet()
if internet == 0:
print(chatbot_tools.random_output('read space article'))
else:
print(chatbot_tools.random_output('no internet'))
def scan_url(website):
url = "https://www.virustotal.com/vtapi/v2/url/scan"
payload = {
"url": website,
"apikey": "72f45ce5dc2e31acfa8362afca81da27f35f6918e90e0caa3b49da9c01c6eb23"
}
headers = {
"accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
}
response = requests.post(url, data=payload, headers=headers)
if response.status_code == 200:
print(chatbot_tools.random_output('wait for scanning'))
get_scan_result(url)
else:
print(chatbot_tools.random_output('scanning failed'))
def get_scan_result(url):
url = 'https://www.virustotal.com/vtapi/v2/url/report'
params = {'apikey': '72f45ce5dc2e31acfa8362afca81da27f35f6918e90e0caa3b49da9c01c6eb23', 'resource':url}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
number_of_unsafe_scans = data['positives']
if number_of_unsafe_scans > 3 and number_of_unsafe_scans < 6: #might be unsafe but is unlikley
print(chatbot_tools.random_output('maybe safe website scan').replace('<unsafe-scans>', str(number_of_unsafe_scans)))
elif number_of_unsafe_scans >= 6:#unsafe don't visit
print(chatbot_tools.random_output('unsafe website'))
else:#completley safe
print(chatbot_tools.random_output('safe website scan'))
def search_food(food):
matching_recipe = recipe_by_title(food)
try:
print(matching_recipe[0]['strMeal'])
ingedients = []
iterable_number = 1
for i in matching_recipe[0]:
try:
if matching_recipe[0]["strIngredient" + str(iterable_number)] != '':
ingedients.append(matching_recipe[0]["strIngredient" + str(iterable_number)])
iterable_number += 1
except:
pass
print("Required Ingredients")
print('\n'.join(ingedients) + "\n")
print(matching_recipe[0]['strInstructions'])
except TypeError:
pass
def search_food_ingriedents(food):
matching_recipe = recipe_by_title(food)
print(matching_recipe[0]['strMeal'])
ingedients = []
iterable_number = 1
for i in matching_recipe[0]:
try:
if matching_recipe[0]["strIngredient" + str(iterable_number)] != '':
ingedients.append(matching_recipe[0]["strIngredient" + str(iterable_number)])
iterable_number += 1
except:
pass
print("Required Ingedients")
print('\n'.join(ingedients) + "\n")
def random_food():
with open('data/datasets/recipies.json', 'r') as f:
data = json.load(f)
try:
random_recipe = random.choice(data)
random_meal = random.choice(random_recipe["meals"])
# Access details of the random meal
meal_name = random_meal["strMeal"]
meal_category = random_meal["strCategory"]
meal_instructions = random_meal["strInstructions"]
print(meal_name)
print(chatbot_tools.random_output('more info on food'))
with open('data/tempFile.txt', 'w') as f:
f.write(meal_name)
except TypeError:
random_food()
def suggest_meal():
user_data = chatbot_tools.get_user_data()
if user_data['favourite food'] != '':
print(chatbot_tools.random_output('suggest favourite food'))
search_food(user_data['favourite food'])
else:
print(chatbot_tools.random_output('suggest random food'))
random_food()