Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import random
- import socket
- import time
- import datetime
- def main():
- global connected
- global response
- global commentedAboutGreet
- # Receive message from client
- receivedMess = conn.recv(1024).decode()
- # Write received message to log file
- writeToLog('User', receivedMess)
- #Print received message from user to the standard output
- print ('Message from User to ChatBot:\t' + str(receivedMess))
- # Check if there is no received message or if 'end' command is received
- if not receivedMess or receivedMess == 'end':
- # Disconnect by setting the condition of the while loop to False and return from the function
- connected = False
- return 1
- # Make 'response' an empty list that will be filled up later
- response = []
- # Parse the user's message into filtered, split words
- parsedUserInput = parseInput(receivedMess)
- # Set this bool to False, as we want to comment about repetitive greetings once for every individual message
- commentedAboutGreet = False
- # Check the user's message for keywords
- for word in parsedUserInput:
- checkForGreeting(word)
- checkForBye(word)
- checkForIll(word)
- checkForAngry(word)
- checkForSad(word)
- checkForGood(word)
- # Ask a casual question if the bot only responds with a single greeting
- askCasual()
- # Make the ChatBot's answer message by parsing the response into a single string
- returnMess = parseOutput(response)
- # Write the ChatBot's answer message to the log
- writeToLog('ChatBot', returnMess)
- print('Message from ChatBot to User:\t' + returnMess)
- conn.send(returnMess.encode())
- def parseInput(sentence):
- """Takes string as input, filters it to only alfanumerical characters,
- then splits the string into words and returns the words as a list of strings."""
- # Make the input sentence lowercase
- sentence = sentence.lower()
- filteredSentence = ""
- # For loop to iterate through all characters of the input message
- for char in sentence:
- # If the given character of the input message is among the alfanumerical characters, add it to the new variable
- if char in '1234567890qwertyuiopasdfghjklzxcvbnm ':
- filteredSentence += char
- # Return the filtered input message split into a list of strings
- return filteredSentence.split()
- def checkForGreeting(word):
- """Takes string as input, checks if it is among the 'greeting keywords',
- if yes, checks for previous greeings and whether it has already commented about being greeted more than once.
- Greeting or comment on being alrady greeted is appended to the list of string 'response'."""
- global response
- global greeted
- global commentedAboutGreet
- # Checks whether the current word is among the greeting keywords
- if word in GREETING_KEYWORDS:
- # Checks if the ChatBot has already been greeted
- if not greeted:
- # If the chatbot hasn't been greeted already, it greets the user,
- # appends a random greeting to the answer
- response.append(random.choice(GREETINGS))
- # Indicating that the ChatBot has been greeted
- greeted = True
- # Checks if the ChatBot has already commented about being greeted twice in this response cycle.
- elif not commentedAboutGreet:
- # Comment to the user about having already been greeted
- response.append('You have already greeted me, but hello again, my friend.')
- # Indicating that the ChatBot has commented about being greeted twice
- commentedAboutGreet = True
- def checkForBye(word):
- """Takes string as input, checks if it is among the 'bye keywords',
- if yes, append the 'response' list with a goodbye."""
- global response
- # Checks whether the current word is among the 'bye keywords'
- if word in BYE_KEYWORDS:
- # Append the 'response' list by a random form of saying 'bye'
- response.append(random.choice(BYE_KEYWORDS).capitalize())
- def checkForIll(word):
- """Takes string as input, appends 'response' list with a random reaction to the illness if input is among the keywords."""
- global response
- # Checks if input is in the 'ill' keywords
- if word in ILL_KEYWORDS:
- # Appends the response with a random reaction to the illness
- response.append(random.choice(BAD_SENTENCE_STARTERS) + ' ' + word + '.')
- def checkForAngry(word):
- """Takes string as input, appends 'response' list with a random reaction to the angryness
- and a motivational quote if input is among the keywords."""
- global response
- # Checks if input is in the 'angry' keywords
- if word in ANGRY_KEYWORDS:
- # Appends the response with a random reaction to the angryness and a motivational quote
- response.append(random.choice(BAD_SENTENCE_STARTERS) + ' ' + word + '. Here is a motivational quote to calm you down:')
- response.append(random.choice(ANGRY_MOTIVATIONAL_QUOTES) + '.')
- def checkForSad(word):
- """Takes string as input, appends 'response' list with a random reaction to the sadness,
- a motivational quote and a joke if input is among the keywords."""
- global response
- # Checks if input is in the 'sad' keywords
- if word in SAD_KEYWORDS:
- # Appends the 'response' list with a random reaction to the sadness, a motivational quote and a joke
- response.append(random.choice(BAD_SENTENCE_STARTERS) + ' ' + word + '. Here is a motivational quote to cheer you up:')
- response.append(random.choice(SAD_MOTIVATIONAL_QUOTES) + '.')
- response.append('Or, if I failed miserably, let me crack a joke:')
- response.append(random.choice(JOKES))
- def checkForGood(word):
- """Takes string as input, appends 'response' list with a random reaction to the 'good' state of mind, and a joke."""
- global response
- # Checks if input is in the 'good' keywords
- if word in GOOD_KEYWORDS:
- # Appends the 'response' list with a random reaction to the good state of mind, and a joke
- response.append(random.choice(GOOD_SENTENCE_STARTERS) + ' ' + word + '. Maybe I could top that, you will find this funny:')
- response.append(random.choice(JOKES))
- def askCasual():
- """Doesn't take any inputs, nor gives outputs. If the 'response' list only contains a greeting,
- then asks a casual question to further the discussion."""
- # Checks if the 'response' list is exactly 1 long, and if it is, then if its only element is a greeting
- if len(response) == 1 and response[0] in GREETINGS:
- # Appends the 'response' list with a random casual question
- response.append(random.choice(CASUAL_QUESTIONS))
- def parseOutput(words):
- """Takes a list of strings as input and outputs them in a single string with a space character between the elements.
- Or, if the input is an empty list, then it returns a default answer"""
- # Check if input is an empty list
- if words == []:
- # Return default answer
- return "Sorry, I didn't catch that. Could you please rephrase it?"
- # Make the output string the first element of the input list
- textOutPut = words[0]
- # Iterate through the elements of the input list starting from the second element
- for i in range(1, len(words)):
- # Add a space character and the next element of the input list to the output string
- textOutPut += " " + words[i]
- # Return the output string
- return textOutPut
- def writeToLog(sender, text):
- """Takes two strings as input, first one is the name of the sender, second one is the message.
- Writes both of the input strings to a text file 'log.txt' along with the current time."""
- # Open file 'log.txt' in 'append' mode so that we don't overwrite the previous log entries
- log = open('log.txt', 'a')
- # Write the current date, time, the sender, and text of the message into the file
- log.write(str(datetime.datetime.now()) + ' ' + sender + ' :\t' + text + '\n')
- # Close the file properly
- log.close()
- GREETING_KEYWORDS = ('hi', 'hey', 'yo', 'hello')
- BYE_KEYWORDS = ('bye', 'goodbye', 'seeya')
- GREETINGS = ('Sup bro?', 'Hey!', 'Hello!', 'Hi!', 'Greetings.', 'Sup?', 'Yo!', 'Hey there!')
- CASUAL_QUESTIONS = ("What's up?", "Wassup?", "How are you doing?")
- GOOD_KEYWORDS = ('happy', 'euphoric', 'fantastic', 'great', 'amazing', 'good', 'alright')
- ILL_KEYWORDS = ('ill', 'sick')
- ANGRY_KEYWORDS = ('angry', 'furious', 'frustrated', 'fuming', 'annoyed', 'pissed off', 'enraged', 'irritated', 'cross')
- SAD_KEYWORDS = ('sad', 'unhappy', 'upset', 'down', 'heartbroken', 'pessimistic', 'depressed', 'dejected')
- BAD_SENTENCE_STARTERS = ("It sucks to be", "Don't be", "It is bad to be")
- GOOD_SENTENCE_STARTERS = ('It is great that you are feeling', 'nice to see you are doing', 'Ayy nice man. Glad you are feeling ', 'I am releived that you feel')
- ANGRY_MOTIVATIONAL_QUOTES = ('"If you get angry easily, it may be because the seed of anger in you has been watered frequently over many years, and unfortunately you have allowed it or even encouraged it to be watered." - Thich Nhat Hanh',
- '"Speak when you are angry – and you’ll make the best speech you’ll ever regret." - Laurence J. Peter',
- '"Where there is anger, there is always pain underneath." - Eckhart Tolle',
- '"Holding on to anger is like grasping a hot coal with the intent of throwing it at someone else; you are the one who gets burned." - Buddha',
- '"For every minute you are angry you lose sixty seconds of happiness." - Ralph Waldo Emerson',
- '"Hanging onto resentment is letting someone you despise live rent-free in your head." - Esther Lederer',
- '"Throughout life people will make you mad, disrespect you and treat you bad. Let God deal with the things they do, cause hate in your heart will consume you too." - Will Smith',
- '"Happiness cannot come from hatred or anger. Nobody can say, <<Today I am happy because this morning I was angry.>> On the contrary, people feel uneasy and sad and say, <<Today I am not very happy, because I lost my temper this morning.>>" - Dalai Lama',
- '"Anybody can become angry — that is easy, but to be angry with the right person and to the right degree and at the right time and for the right purpose, and in the right way — that is not within everybody’s power and is not easy." - Aristole')
- SAD_MOTIVATIONAL_QUOTES = ("'Some days are just bad days, that's all. You have to experience sadness to know happiness, and I remind myself that not every day is going to be a good day, that's just the way it is!' - Dite von Teese",
- "'Every human walks around with a certain kind of sadness. They may not wear it on their sleeves, but it's there if you look deep.' - Taraji P. Henson",
- '"The word <happy> would lose its meaning if was not balanced by sadness" - Carl Jung')
- JOKES = ("I went to the funeral of a friend recently who had drowned. We were going to get him a floral wreath, but instead we decided on a life raft. It's what he would have wanted.",
- "What has 4 wheels and flies? A garbage truck.",
- "What did the snowman say? Smells like carrots.",
- "When is a car not a car? When it turns into a driveway.",
- "A wolf walks into a bar and says 'I'll have a........ beer.' Barman says 'Why the long pause?'",
- "Where does the president keep his armies? In his sleevies.")
- # Make boolean variable indicating whether the client is connected
- connected = False
- # Give the ChatBot its IP address, it's localhost, as the client is running on the same machiney
- host = '127.0.0.1'
- # Give the port number used by both the client and the server, has to be the same on both ends
- port = 5003
- # Create Socket and bind server to socket
- thisSocket = socket.socket()
- thisSocket.bind((host,port))
- # Listen for clients
- thisSocket.listen(1)
- # Connect to client
- conn, addr = thisSocket.accept()
- # Print the connected ip address
- print ('The Connection ip is: ' + str(addr))
- # Set the boolean variable to True, indicatend that the connection has been established
- connected = True
- # Set bool boolean variable to its starting value, indicating that the ChatBot hasn't been greeted
- greeted = False
- # Runs the 'main' function as long the client is connected
- while connected:
- if __name__ == '__main__':
- main()
- # Closes down the connection to the client
- conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement