Sobsz

the epicest of bots (now on http://github.com/Sobsz/EpicBot)

Nov 13th, 2018
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.58 KB | None | 0 0
  1. import os
  2. import random
  3. from difflib import SequenceMatcher
  4.  
  5. filename = "database.txt" # i didn't want to put a comment here but it looks weird otherwise so e
  6. max_responses = 0         # now you can automatically inflict amnesia to your robot friend!
  7. learn = True              # disable if you want to keep your database pristine (MANUAL LEARN COMMANDS ARE STILL USABLE)
  8. debug = False             # shows the potential responses as well as "accuracy"
  9. bot_goes_first = False    # i recommend leaving this off during the first few phases of training so the bot can learn some greetings
  10.                           # (if you want to teach some manually just leave the "if someone says..." part blank)
  11. class chatbot:
  12.     """epic retrieval-based chatbot of minimal complexity (and effectiveness)"""
  13.  
  14.     def __init__(self, max_responses = 0, responses = [("hello", "hi")]):
  15.         self.max_responses = max_responses
  16.         self.responses = responses
  17.  
  18.     def clean(self, s):
  19.         stripped = s.strip().translate(str.maketrans("", "", ".,?!:;'\"()*_")).lower()
  20.         if debug:
  21.             print("# " + stripped)
  22.         if stripped == "":
  23.             return s
  24.         else:
  25.             return stripped
  26.    
  27.     def dist(self, a, b):
  28.         return SequenceMatcher(None, a, b).ratio()
  29.    
  30.     def respond(self, query):
  31.         query_cleaned = self.clean(query)
  32.         temp = [(self.dist(i[0], query_cleaned), i[1]) for i in self.responses]
  33.         best_dist = -1
  34.         best_responses = ["ERROR: IF YOU SEE THIS THEN SOMETHING IS WRONG WITH THE RESPONSE LIST AND THAT IS NOT A GOOD THING"]
  35.         for i in temp:
  36.             if i[0] > best_dist:
  37.                 best_dist = i[0]
  38.                 best_responses = [i[1]]
  39.             elif i[0] == best_dist:
  40.                 best_responses.append(i[1])
  41.         if debug:
  42.             print("# accuracy: " + str(best_dist))
  43.             print("# list: " + str(best_responses))
  44.         return random.choice(best_responses)
  45.  
  46.     def learn(self, query, response):
  47.         self.responses.append((self.clean(query), response))
  48.         if self.max_responses > 0:
  49.             if len(self.responses) > self.max_responses:
  50.                 self.responses.pop(0)
  51.  
  52. print("* EpicBot v6.2.1 - made by zsboS#8977")
  53. print("* Loading database...")
  54. try:
  55.     file = open(filename)
  56.     if os.path.getsize(filename) == 0:
  57.         raise IOError
  58.     bot = chatbot(max_responses, eval(file.read()))
  59.     file.close()
  60.     print("* Successfully loaded " + str(len(bot.responses)) + " entries.")
  61. except IOError:
  62.     bot = chatbot()
  63.     print("* Database does not exist, creating...")
  64.     file = open(filename, "w")
  65.     file.write(repr(bot.responses))
  66.     file.close()
  67.     print("* Successfully created database.")
  68. except ValueError:
  69.     print("* Database may be corrupt! Please remove or rename the " + filename + " file, then restart.")
  70.     input("* Press Enter to continue...")
  71.     exit()
  72.  
  73. print("* EpicBot is now ready for your input.")
  74. if bot_goes_first:
  75.     response = bot.respond("")
  76.     print("< " + response)
  77. else:
  78.     response = ""
  79.  
  80. while True:
  81.     query = input("> ")
  82.     if query:
  83.         if query[0] == "/":
  84.             if query in ("/learn", "/l", "/teach", "/t"):
  85.                 print("* If someone says...")
  86.                 learn_query = input("> ")
  87.                 print("* The bot should respond with...")
  88.                 learn_response = input("> ")
  89.                 bot.learn(learn_query, learn_response)
  90.                 print("* Taught successfully!")
  91.             elif query in ("/save", "/s"):
  92.                 print("* Saving " + str(len(bot.responses)) + " entries...")
  93.                 file = open(filename, "w")
  94.                 file.write(repr(bot.responses))
  95.                 file.close()
  96.                 if debug:
  97.                     print(repr(bot.responses))
  98.                 print("* Successfully saved database!")
  99.             elif query in ("/quit", "/q", "exit", "/e"):
  100.                 print("* Are you sure? All unsaved changes will be lost! (Y/N)")
  101.                 if input("> ")[0].lower() == "y":
  102.                     print("* Quitting...")
  103.                     quit()
  104.                 else:
  105.                     print("* Quit operation cancelled.")
  106.             elif query in ("/count", "/c"):
  107.                 print("* Amount of entries: " + str(len(bot.responses)))
  108.             elif query in ("/dump", "/d"):
  109.                 print("* " + str(bot.responses))
  110.                 print("* Amount of entries: " + str(len(bot.responses)))
  111.             elif query in ("/undo", "/u"):
  112.                 print("* Successfully removed:" + str(bot.responses.pop()))
  113.             elif query in ("/help", "/h", "/?"):
  114.                 print("* Available commands:")
  115.                 print("* /help (/?)      - prints this list")
  116.                 print("* /learn (/teach) - lets you teach the bot something manually")
  117.                 print("* /undo           - removes the latest response")
  118.                 print("* /save           - saves the response database")
  119.                 print("* /dump           - outputs the current database along with the entry count")
  120.                 print("* /count          - outputs just the entry count")
  121.                 print("* /quit (/exit)   - leaves the program")
  122.                 print("* You can use the first letter of a command as a shortcut, like so: '/s'")
  123.             else:
  124.                 print("* Unknown command! Type /help to list the available commands.")
  125.         else:
  126.             if learn:
  127.                 bot.learn(response, query)
  128.             response = bot.respond(query)
  129.             print("< " + response)
Add Comment
Please, Sign In to add comment