Advertisement
Boba0514

serverScript.py

Nov 24th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.76 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import random
  4. import socket
  5. import time
  6. import datetime
  7.  
  8. def main():
  9.     global connected
  10.     global response
  11.     global commentedAboutGreet
  12.    
  13.     # Receive message from client
  14.     receivedMess = conn.recv(1024).decode()
  15.    
  16.     # Write received message to log file
  17.     writeToLog('User', receivedMess)
  18.    
  19.     #Print received message from user to the standard output
  20.     print ('Message from User to ChatBot:\t' + str(receivedMess))
  21.    
  22.     # Check if there is no received message or if 'end' command is received
  23.     if not receivedMess or receivedMess == 'end':
  24.         # Disconnect by setting the condition of the while loop to False and return from the function
  25.         connected = False
  26.         return 1
  27.  
  28.     # Make 'response' an empty list that will be filled up later
  29.     response = []
  30.    
  31.     # Parse the user's message into filtered, split words
  32.     parsedUserInput = parseInput(receivedMess)
  33.  
  34.     # Set this bool to False, as we want to comment about repetitive greetings once for every individual message
  35.     commentedAboutGreet = False
  36.    
  37.     # Check the user's message for keywords
  38.     for word in parsedUserInput:
  39.         checkForGreeting(word)
  40.         checkForBye(word)
  41.         checkForIll(word)
  42.         checkForAngry(word)
  43.         checkForSad(word)
  44.         checkForGood(word)
  45.  
  46.     # Ask a casual question if the bot only responds with a single greeting
  47.     askCasual()
  48.  
  49.     # Make the ChatBot's answer message by parsing the response into a single string
  50.     returnMess = parseOutput(response)
  51.  
  52.     # Write the ChatBot's answer message to the log
  53.     writeToLog('ChatBot', returnMess)
  54.     print('Message from ChatBot to User:\t' + returnMess)
  55.     conn.send(returnMess.encode())
  56.  
  57. def parseInput(sentence):
  58.     """Takes string as input, filters it to only alfanumerical characters,
  59.     then splits the string into words and returns the words as a list of strings."""
  60.     # Make the input sentence lowercase
  61.     sentence = sentence.lower()
  62.     filteredSentence = ""
  63.     # For loop to iterate through all characters of the input message
  64.     for char in sentence:
  65.         # If the given character of the input message is among the alfanumerical characters, add it to the new variable
  66.         if char in '1234567890qwertyuiopasdfghjklzxcvbnm ':
  67.             filteredSentence += char
  68.  
  69.     # Return the filtered input message split into a list of strings
  70.     return filteredSentence.split()
  71.  
  72. def checkForGreeting(word):
  73.     """Takes string as input, checks if it is among the 'greeting keywords',
  74.     if yes, checks for previous greeings and whether it has already commented about being greeted more than once.
  75.     Greeting or comment on being alrady greeted is appended to the list of string 'response'."""
  76.     global response
  77.     global greeted
  78.     global commentedAboutGreet
  79.     # Checks whether the current word is among the greeting keywords
  80.     if word in GREETING_KEYWORDS:
  81.         # Checks if the ChatBot has already been greeted
  82.         if not greeted:
  83.             # If the chatbot hasn't been greeted already, it greets the user,
  84.             # appends a random greeting to the answer
  85.             response.append(random.choice(GREETINGS))
  86.             # Indicating that the ChatBot has been greeted
  87.             greeted = True
  88.         # Checks if the ChatBot has already commented about being greeted twice in this response cycle.
  89.         elif not commentedAboutGreet:
  90.             # Comment to the user about having already been greeted
  91.             response.append('You have already greeted me, but hello again, my friend.')
  92.             # Indicating that the ChatBot has commented about being greeted twice
  93.             commentedAboutGreet = True
  94.  
  95. def checkForBye(word):
  96.     """Takes string as input, checks if it is among the 'bye keywords',
  97.     if yes, append the 'response' list with a goodbye."""
  98.     global response
  99.     # Checks whether the current word is among the 'bye keywords'
  100.     if word in BYE_KEYWORDS:
  101.         # Append the 'response' list by a random form of saying 'bye'
  102.         response.append(random.choice(BYE_KEYWORDS).capitalize())
  103.  
  104. def checkForIll(word):
  105.     """Takes string as input, appends 'response' list with a random reaction to the illness if input is among the keywords."""
  106.     global response
  107.     # Checks if input is in the 'ill' keywords
  108.     if word in ILL_KEYWORDS:
  109.         # Appends the response with a random reaction to the illness
  110.         response.append(random.choice(BAD_SENTENCE_STARTERS) + ' ' + word + '.')
  111.  
  112.  
  113. def checkForAngry(word):
  114.     """Takes string as input, appends 'response' list with a random reaction to the angryness
  115.     and a motivational quote if input is among the keywords."""
  116.     global response
  117.     # Checks if input is in the 'angry' keywords
  118.     if word in ANGRY_KEYWORDS:
  119.         # Appends the response with a random reaction to the angryness and a motivational quote
  120.         response.append(random.choice(BAD_SENTENCE_STARTERS) + ' ' + word + '. Here is a motivational quote to calm you down:')
  121.         response.append(random.choice(ANGRY_MOTIVATIONAL_QUOTES) + '.')
  122.  
  123. def checkForSad(word):
  124.     """Takes string as input, appends 'response' list with a random reaction to the sadness,
  125.     a motivational quote and a joke if input is among the keywords."""
  126.     global response
  127.     # Checks if input is in the 'sad' keywords
  128.     if word in SAD_KEYWORDS:
  129.         # Appends the 'response' list with a random reaction to the sadness, a motivational quote and a joke
  130.         response.append(random.choice(BAD_SENTENCE_STARTERS) + ' ' + word + '. Here is a motivational quote to cheer you up:')
  131.         response.append(random.choice(SAD_MOTIVATIONAL_QUOTES) + '.')
  132.         response.append('Or, if I failed miserably, let me crack a joke:')
  133.         response.append(random.choice(JOKES))
  134.  
  135. def checkForGood(word):
  136.     """Takes string as input, appends 'response' list with a random reaction to the 'good' state of mind, and a joke."""
  137.     global response
  138.     # Checks if input is in the 'good' keywords
  139.     if word in GOOD_KEYWORDS:
  140.         # Appends the 'response' list with a random reaction to the good state of mind, and a joke
  141.         response.append(random.choice(GOOD_SENTENCE_STARTERS) + ' ' + word + '. Maybe I could top that, you will find this funny:')
  142.         response.append(random.choice(JOKES))
  143.  
  144. def askCasual():
  145.     """Doesn't take any inputs, nor gives outputs. If the 'response' list only contains a greeting,
  146.     then asks a casual question to further the discussion."""
  147.     # Checks if the 'response' list is exactly 1 long, and if it is, then if its only element is a greeting
  148.     if len(response) == 1 and response[0] in GREETINGS:
  149.         # Appends the 'response' list with a random casual question
  150.         response.append(random.choice(CASUAL_QUESTIONS))
  151.  
  152. def parseOutput(words):
  153.     """Takes a list of strings as input and outputs them in a single string with a space character between the elements.
  154.     Or, if the input is an empty list, then it returns a default answer"""
  155.     # Check if input is an empty list
  156.     if words == []:
  157.         # Return default answer
  158.         return "Sorry, I didn't catch that. Could you please rephrase it?"
  159.     # Make the output string the first element of the input list
  160.     textOutPut = words[0]
  161.     # Iterate through the elements of the input list starting from the second element
  162.     for i in range(1, len(words)):
  163.         # Add a space character and the next element of the input list to the output string
  164.         textOutPut += " " + words[i]
  165.     # Return the output string
  166.     return textOutPut
  167.  
  168. def writeToLog(sender, text):
  169.     """Takes two strings as input, first one is the name of the sender, second one is the message.
  170.     Writes both of the input strings to a text file 'log.txt' along with the current time."""
  171.     # Open file 'log.txt' in 'append' mode so that we don't overwrite the previous log entries
  172.     log = open('log.txt', 'a')
  173.     # Write the current date, time, the sender, and text of the message into the file
  174.     log.write(str(datetime.datetime.now()) + ' ' + sender + ' :\t' + text + '\n')
  175.     # Close the file properly
  176.     log.close()
  177.  
  178. GREETING_KEYWORDS = ('hi', 'hey', 'yo', 'hello')
  179.  
  180. BYE_KEYWORDS = ('bye', 'goodbye', 'seeya')
  181.  
  182. GREETINGS = ('Sup bro?', 'Hey!', 'Hello!', 'Hi!', 'Greetings.', 'Sup?', 'Yo!', 'Hey there!')
  183.  
  184. CASUAL_QUESTIONS = ("What's up?", "Wassup?", "How are you doing?")
  185.  
  186. GOOD_KEYWORDS = ('happy', 'euphoric', 'fantastic', 'great', 'amazing', 'good', 'alright')
  187.  
  188. ILL_KEYWORDS = ('ill', 'sick')
  189.  
  190. ANGRY_KEYWORDS = ('angry', 'furious', 'frustrated', 'fuming', 'annoyed', 'pissed off', 'enraged', 'irritated', 'cross')
  191.  
  192. SAD_KEYWORDS = ('sad', 'unhappy', 'upset', 'down', 'heartbroken', 'pessimistic', 'depressed', 'dejected')
  193.  
  194. BAD_SENTENCE_STARTERS = ("It sucks to be", "Don't be", "It is bad to be")
  195.  
  196. 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')
  197.  
  198. 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',
  199.     '"Speak when you are angry – and you’ll make the best speech you’ll ever regret." - Laurence J. Peter',
  200.     '"Where there is anger, there is always pain underneath." - Eckhart Tolle',
  201.     '"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',
  202.     '"For every minute you are angry you lose sixty seconds of happiness." - Ralph Waldo Emerson',
  203.     '"Hanging onto resentment is letting someone you despise live rent-free in your head." - Esther Lederer',
  204.     '"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',
  205.     '"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',
  206.     '"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')
  207.  
  208. 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",
  209.     "'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",
  210.     '"The word <happy> would lose its meaning if was not balanced by sadness" - Carl Jung')
  211.  
  212. 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.",
  213.     "What has 4 wheels and flies? A garbage truck.",
  214.     "What did the snowman say? Smells like carrots.",
  215.     "When is a car not a car? When it turns into a driveway.",
  216.     "A wolf walks into a bar and says 'I'll have a........ beer.' Barman says 'Why the long pause?'",
  217.     "Where does the president keep his armies? In his sleevies.")
  218.  
  219. # Make boolean variable indicating whether the client is connected
  220. connected = False
  221.  
  222. # Give the ChatBot its IP address, it's localhost, as the client is running on the same machiney
  223. host = '127.0.0.1'
  224. # Give the port number used by both the client and the server, has to be the same on both ends
  225. port = 5003
  226. # Create Socket and bind server to socket
  227. thisSocket = socket.socket()
  228. thisSocket.bind((host,port))
  229. # Listen for clients
  230. thisSocket.listen(1)
  231. # Connect to client
  232. conn, addr = thisSocket.accept()
  233. # Print the connected ip address
  234. print ('The Connection ip is: ' + str(addr))
  235.  
  236. # Set the boolean variable to True, indicatend that the connection has been established
  237. connected = True
  238.  
  239. # Set bool boolean variable to its starting value, indicating that the ChatBot hasn't been greeted
  240. greeted = False
  241.  
  242. # Runs the 'main' function as long the client is connected
  243. while connected:
  244.     if __name__ == '__main__':
  245.         main()
  246. # Closes down the connection to the client
  247. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement