From 2c766c40e98dcbdeb56a389c9791d710848058b0 Mon Sep 17 00:00:00 2001 From: "Andris Jansons (jansonsa)" Date: Mon, 20 Nov 2017 21:32:13 +0000 Subject: [PATCH] Add files via upload --- FoodFinder.py | 13 ++++++------- GUI.py | 44 +++++++++++++++++++++++++------------------- Greetings.py | 6 +++--- QuestionToList.py | 1 + ResponseGenerator.py | 25 +++++++++++++------------ RiotAPI.py | 3 +++ SentenceSplitter.py | 2 ++ WeatherFinder.py | 17 +++++++++-------- dataData.txt | 2 +- leagueInit.py | 5 +++-- placeFinderFinal.py | 9 +++++---- placeInit.py | 9 +++++++-- server1.py | 31 ++++++++++++++++++------------- weatherInit.py | 5 ++++- 14 files changed, 100 insertions(+), 72 deletions(-) diff --git a/FoodFinder.py b/FoodFinder.py index 377d06c..8016db4 100644 --- a/FoodFinder.py +++ b/FoodFinder.py @@ -1,25 +1,24 @@ - +# Made by Andris Jansons KEYWORDS = "the, a, an, get, good, best, is, are, to, nice, pleasant, lovely, cool, fine, stupid, goddamn, great, large, small, medium, new, newest, old, closest, smallest, biggest, coolest".split(", ") - def findFood(text): """Finds food after special KEYWORDS""" found = False food = "" - for word in text: + for word in text: if found == False: if word == "get": continue if word in KEYWORDS: - found = True + found = True #Finds the first keyword food = word else: if word in KEYWORDS: food = food + " " + word continue - food = food + " " + word - break - return food + food = food + " " + word #If multiple keywords follow each other + break # take all of them in account and the word + return food # that follows them as well e.g. "The best burger" diff --git a/GUI.py b/GUI.py index 9989479..e9c4f32 100644 --- a/GUI.py +++ b/GUI.py @@ -17,24 +17,30 @@ def disableEntry(event): entryBox.config(state=DISABLED) def clickAction(): - global FirstEntry - global userName - if FirstEntry == True: - FirstEntry = False - userName = entryBox.get("0.0", END)[:-1] - savePreferences(userName) - entryText = filteredMessage(entryBox.get("0.0", END)) - loadMyEntry(chatDispl, entryText) - client.send( entryText.encode('utf-8') ) # Encode the messsage in bits and send it to server - - rawmsg = client.recv(1024) # recieve up to 1024 bytes - - msg = rawmsg.decode('utf-8').rstrip('\r\n') # Decode received message from bits to string - loadOtherEntry(chatDispl, msg) - - chatDispl.yview(END)#Scroll to the bottom of chat windows - entryBox.delete("0.0", END) #Erace previous message in Entry Box - + try: + global FirstEntry + global userName + if FirstEntry == True: # When you send the first message + FirstEntry = False + userName = entryBox.get("0.0", END)[:-1] + inDatabase = readFunction(userName) + if inDatabase == False: + savePreferences(userName) + entryText = filteredMessage(entryBox.get("0.0", END)) + loadMyEntry(chatDispl, entryText) + client.send( entryText.encode('utf-8') ) # Encode the messsage in bits and send it to server + try: + rawmsg = client.recv(1024) # recieve up to 1024 bytes + + msg = rawmsg.decode('utf-8').rstrip('\r\n') # Decode received message from bits to string + loadOtherEntry(chatDispl, msg) + except: + print("Didnt receive a message") + chatDispl.yview(END)#Scroll to the bottom of chat windows + entryBox.delete("0.0", END) #Erace previous message in Entry Box + except: + client.shutdown(1) + print("Shutdown") def filteredMessage(entryText): """ @@ -98,7 +104,7 @@ entryBox.bind("", pressAction) scrollBar.place(x=576,y=6, height=386) chatDispl.place(x=6,y=6, height=386, width=570) -entryBox.place(x=128, y=401, height=90, width=465) +entryBox.place(x=138, y=401, height=90, width=465) sendBtn.place(x=6, y=401, height=90) base.mainloop() diff --git a/Greetings.py b/Greetings.py index c437b64..65b6f77 100644 --- a/Greetings.py +++ b/Greetings.py @@ -1,9 +1,9 @@ - +#Made by Andris Jansons def isGreeted(text): """Checks if user greets the program and if the greeting is formal or not""" KEYWORDS_FORMAL = "hi, hello".split(", ") - KEYWORDS_UNFORMAL = "hey, heya, aloha, wassup, hola".split(", ") + KEYWORDS_UNFORMAL = "hey, heya, aloha, wassup, hola, ola, heyy, sup, yo".split(", ") greeted = False formal = False for word in text: @@ -15,4 +15,4 @@ def isGreeted(text): greeted = True break - return greeted, formal + return greeted, formal # Both booleans diff --git a/QuestionToList.py b/QuestionToList.py index 295ef71..97a9c0e 100644 --- a/QuestionToList.py +++ b/QuestionToList.py @@ -1,3 +1,4 @@ +# Made by Andris Jansons import string def makeList(text): """Removes punctation, makes all words lowercase and makes a list""" diff --git a/ResponseGenerator.py b/ResponseGenerator.py index af4f75d..cbd2a96 100644 --- a/ResponseGenerator.py +++ b/ResponseGenerator.py @@ -1,3 +1,4 @@ +# Made by Andris Jansons from Greetings import isGreeted from weatherInit import weatherInit from placeInit import placeInit @@ -5,28 +6,32 @@ from QuestionToList import makeList from datetime import datetime from leagueInit import leagueInit import random + def generateResponse(sentence, lastSentence): + """Based on users sentence, call the appropriate branch of the bot""" sentence = makeList(sentence) lastSentence = makeList(lastSentence) response = "" - greeted, formal = isGreeted(sentence) # 2 booleans - if greeted and formal: - response = "Hi! " + + greeted, formal = isGreeted(sentence) # Greet the user back + if greeted and formal: # Greeting gets added at the start of the response + response = "Hi! " elif greeted: response = "Hey! " - if "where" in sentence or "want" in sentence or "whereabouts" in sentence: #Find out where the user is + if "where" in sentence or "want" in sentence or "wheres" in sentence or "whereabouts" in sentence: #Find out where the user is return response + "Where are you right now?" - if "where" in lastSentence or "want" in lastSentence or "whereabouts" in lastSentence: #When you know where the user is + if "where" in lastSentence or "want" in lastSentence or "wheres" in sentence or "whereabouts" in lastSentence: #When you know where the user is return response + placeInit(sentence, lastSentence) - + # Above: sentence = location and lastSentence is the user's main question + if "how" in sentence and "counter" in sentence: - return leagueInit(sentence) + return leagueInit(sentence) # Looking for format: e.g. "How to counter Teemo" if 'weather' in sentence or 'temperature' in sentence: return response + weatherInit(sentence) - +# Made by Svaraaj #the following chunk will answer user questions starting with 'What'. Still requires expansion -Svaraaj if "what" in sentence or "whats" in sentence: if "favourite" in sentence: @@ -55,9 +60,5 @@ def generateResponse(sentence, lastSentence): response = response + "I don't like this line of questioning bud. Anyway, how is your life going?" - - - - return response diff --git a/RiotAPI.py b/RiotAPI.py index ff17971..518fe70 100644 --- a/RiotAPI.py +++ b/RiotAPI.py @@ -1,3 +1,4 @@ +#Made by Andris Jansons import json import urllib.request import pickle @@ -22,8 +23,10 @@ def leagueCounterTips(champion): for tip in dataDict[champion]['enemytips']: counterTips = counterTips + tip + "\n" return counterTips[:-1] + except KeyError: # If champion is not found return "There is no champion with that name." + except: # If the file does not exist. because Riot let's us call the api 10 times/hour leagueCounterTipsSet() with open('leagueData.txt', 'rb') as f: diff --git a/SentenceSplitter.py b/SentenceSplitter.py index 81f5c44..e9ad080 100644 --- a/SentenceSplitter.py +++ b/SentenceSplitter.py @@ -1,3 +1,5 @@ +#Not used +#Made by Andris Jansons def sentenceSplitter(text): text = text.lower().split(" ") temp = "" diff --git a/WeatherFinder.py b/WeatherFinder.py index cbd5d92..d679423 100644 --- a/WeatherFinder.py +++ b/WeatherFinder.py @@ -1,17 +1,18 @@ -import pyowm +# Made by Andris Jansons +import pyowm # (In case of errors) pip install pyowm -owm = pyowm.OWM('de3ca9ba44d7bc37ce1279f34c3a0911') # You MUST provide a valid API key +owm = pyowm.OWM('de3ca9ba44d7bc37ce1279f34c3a0911') # You get this at OpenWeatherMap def weatherFinder(location): + """For a specific location get weather data""" observation = owm.weather_at_place(location) - w = observation.get_weather() - print(w) + w = observation.get_weather() # Weather details - desc = w.get_detailed_status() - wind = w.get_wind().get('speed') - humidity = w.get_humidity() + desc = w.get_detailed_status() # e.g. few clouds + wind = w.get_wind().get('speed') # dictionary type + humidity = w.get_humidity() # e.g. 98 temperature = w.get_temperature('celsius').get('temp') # {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0} - return desc, str(temperature), str(wind), str(humidity) + return desc, str(temperature), str(wind), str(humidity) diff --git a/dataData.txt b/dataData.txt index bd0a213..e3ca3b0 100644 --- a/dataData.txt +++ b/dataData.txt @@ -15,4 +15,4 @@ Hi Andris Andris Andris - Andris Andris Andris Where a burger Andris Test User andrisSucks \ No newline at end of file + Andris Andris Andris Where a burger Andris Test User andrisSucks Andris 123 \ No newline at end of file diff --git a/leagueInit.py b/leagueInit.py index 4c9bd8d..56fdabe 100644 --- a/leagueInit.py +++ b/leagueInit.py @@ -1,5 +1,6 @@ from RiotAPI import leagueCounterTips def leagueInit(sentence): + """Initialize League of Legends champion counter tips""" i = sentence.index("counter") - champion = sentence[i+1] - return leagueCounterTips(champion) + champion = sentence[i+1] # The word that follows "counter" is the name of the champion + return leagueCounterTips(champion) diff --git a/placeFinderFinal.py b/placeFinderFinal.py index 60ba0da..9788db5 100644 --- a/placeFinderFinal.py +++ b/placeFinderFinal.py @@ -1,4 +1,5 @@ -from googleplaces import GooglePlaces, types, lang # You need to use googleplaces library +#Made by Andris Jansons +from googleplaces import GooglePlaces, types # You need to use googleplaces library YOUR_API_KEY = 'AIzaSyDOIMYjnWeH8fgT5YaYfrjo4BzEqyHR6PM' #You get this from Google Console @@ -19,8 +20,8 @@ def findPlace(location_str='Coventry University',keyword_str='Food'): radius=radius_int ) #types=[types.TYPE_FOOD] if you need a specific type if len(query_result.places)>0: - break - radius_int = radius_int + 100 + break # If atleast one place is found + radius_int = radius_int + 100 # If not - increase radius if query_result.has_attributions: print (query_result.html_attributions) @@ -28,7 +29,7 @@ def findPlace(location_str='Coventry University',keyword_str='Food'): for place in query_result.places: #For each found place print details - place.get_details() + place.get_details() # An initializer for what's next placeName = place.name placeAddress = place.formatted_address diff --git a/placeInit.py b/placeInit.py index 9e3989d..d7de7ee 100644 --- a/placeInit.py +++ b/placeInit.py @@ -1,11 +1,16 @@ +# Made by Andris Jansons from FoodFinder import findFood from placeFinderFinal import findPlace def placeInit(sentence, lastSentence): + """Initialize place finder""" + food = findFood(lastSentence) #For example: food = the best burger # food can also be: hotel, bank etc. It's just easier to imagine talking about food - placeName, placeAddress, placeWebsite, placePhone = findPlace(sentence, food) + + placeName, placeAddress, placeWebsite, placePhone = findPlace(sentence, food) # We get a tuple back + if not(placeName == None): return "You can get "+food+" at "+placeName+"\nLocation: "+placeAddress - else: #What happens when there is a error in Google Place API + else: #What happens when there is an error in Google Place API return "I don't know where that is" diff --git a/server1.py b/server1.py index 78867c8..e011092 100644 --- a/server1.py +++ b/server1.py @@ -1,3 +1,4 @@ +# Modified by Andris Jansons import socket, time # Import socket module from ResponseGenerator import generateResponse @@ -9,24 +10,28 @@ s.listen(5) # Now wait for client connection. print('Server is running on port {}'.format(port)) try: - temp = "" while True: + temp = "" c, addr = s.accept() # Establish connection with client. print('Got connection from', addr) - while True: - rawmsg = c.recv(1024) # recieve up to 1024 bytes - - msg = rawmsg.decode('utf-8').rstrip('\r\n') # convert and clean the input + while True: + try: + rawmsg = c.recv(1024) # recieve up to 1024 bytes + + msg = rawmsg.decode('utf-8').rstrip('\r\n') # convert and clean the input + + rtrnmsg = generateResponse(msg, temp) # create return message + temp = msg # Keep last message + print( '%s -> %s' % (msg,rtrnmsg) ) + + rtrnmsg = rtrnmsg + '\r\n' + c.send( rtrnmsg.encode('utf-8') ) # send return message + + except ConnectionResetError: # if one client shuts down, wait for next one to connect + print("Closed last connection") + break - rtrnmsg = generateResponse(msg, temp) # create return message - temp = msg - print( '%s -> %s' % (msg,rtrnmsg) ) - - rtrnmsg = rtrnmsg + '\r\n' - c.send( rtrnmsg.encode('utf-8') ) # send return message - - print('Disconnected') c.close() # Close the connection except KeyboardInterrupt: # catch Ctrl-C signals so that we shutdown nicely diff --git a/weatherInit.py b/weatherInit.py index ba99b2a..24c60ce 100644 --- a/weatherInit.py +++ b/weatherInit.py @@ -1,7 +1,10 @@ +# Made by Andris Jansons from WeatherFinder import weatherFinder + def weatherInit(text): + """Find location in sentence or assume it's Coventry and ask for weather details""" try: - if 'in' in text: + if 'in' in text: #Next word after "in" or "for" should be location i = text.index('in') location = text[i+1] elif 'for' in text: