Skip to content
Permalink
Browse files
Add files via upload
  • Loading branch information
jansonsa committed Nov 20, 2017
1 parent 7f78ba7 commit 2c766c40e98dcbdeb56a389c9791d710848058b0
Show file tree
Hide file tree
Showing 14 changed files with 100 additions and 72 deletions.
@@ -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"

44 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("<KeyRelease-Return>", 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()
@@ -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
@@ -1,3 +1,4 @@
# Made by Andris Jansons
import string
def makeList(text):
"""Removes punctation, makes all words lowercase and makes a list"""
@@ -1,32 +1,37 @@
# Made by Andris Jansons
from Greetings import isGreeted
from weatherInit import weatherInit
from placeInit import placeInit
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
@@ -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:
@@ -1,3 +1,5 @@
#Not used
#Made by Andris Jansons
def sentenceSplitter(text):
text = text.lower().split(" ")
temp = ""
@@ -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)

@@ -15,4 +15,4 @@ Hi

Andris
Andris Andris
Andris Andris Andris Where a burger Andris Test User andrisSucks
Andris Andris Andris Where a burger Andris Test User andrisSucks Andris 123
@@ -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)
@@ -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,16 +20,16 @@ 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)


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
@@ -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"
@@ -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
@@ -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:

0 comments on commit 2c766c4

Please sign in to comment.