Skip to content

Instantly share code, notes, and snippets.

@iskander
Created March 8, 2010 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iskander/325055 to your computer and use it in GitHub Desktop.
Save iskander/325055 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# (c) Jan Dlabal (http://houbysoft.com), 2010.
# provided under the GNU GPL v3 License.
from mncmp import mncmp
from sys import argv
from sys import stdout
from os import system
from cmd import Cmd
class Pretzel(Cmd):
def __init__(self):
self.prompt = '> ' #defining promt cmd-style
self.completekey = 'Tab'
self.pretzel_keys = []
print "Loading data... ",
stdout.flush()
try:
if len(argv)==2:
self.datafile = argv[1]
else:
self.datafile = "pretzel.dat"
f = open(self.datafile)
str = f.readline()
while str:
if str[-1]=='\n':
str = str[:-1]
self.pretzel_keys.append([str[:str.find(':')],str[str.find(':')+1:]])
str = f.readline()
print "[done]"
except:
self.pretzel_keys.append(['hello','hi'])
self.pretzel_keys.append(['how are you','fine, thanks'])
self.pretzel_keys.append(['exit','exit'])
self.pretzel_keys.append(['quit','quit'])
print "[failed] (new database will be created in pretzel.dat after a clean exit (type exit to do that))"
print "Initializing mncmp()... ",
stdout.flush()
mncmp("doors","walls") # need to pass anything through it once so that the wordnet dictionnaries get loaded etc.
print "[done]"
def flushdb(self):
f = open(self.datafile,"w")
for item in self.pretzel_keys:
f.write(item[0]+":"+item[1]+"\n")
f.close()
def panic(self):
print "I don't know what to do!"
return raw_input("Please enter desired response (enter text for text reply, or /shell command args to run command with args as response): ")
def default(self,line):
if len(line)==0:
return
if line[0]=='/':
if line[1:7]=='shell ':
system(line[7:])
elif line[1:8]=='python ':
exec(line[8:])
else:
print line
def precmd(self, line): # hook in cmd to digest line input before trying to execute it. Need to return line for it to be executed.
success = False
for item in self.pretzel_keys:
args = mncmp(user,item[0])
itemtmp = item[1]
if args is not False:
if args is not True:
# means we have some arguments
for x in range(0,len(args)):
try:
itemtmp = itemtmp.replace('arg'+repr(x+1),args[x])
except:
pass
success = True
if itemtmp=='exit':
return True
if not success:
line = self.panic()
if line!="":
self.pretzel_keys.append([user, line])
else:
print "Received empty input; not adding to database."
return line #pass user input to execution (default or others)
def postcmd(self, stop, line):
self.flushdb()
p = Pretzel()
p.cmdloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment