Cleverbot: Use better coding style.

master
Valentin Lorentz 2013-06-16 10:44:47 +02:00
parent 99bc9846e0
commit bd1367ee91
7 changed files with 195 additions and 185 deletions

0
Cleverbot/LICENSE.txt Executable file → Normal file
View File

0
Cleverbot/README.txt Executable file → Normal file
View File

5
Cleverbot/__init__.py Executable file → Normal file
View File

@ -37,8 +37,9 @@ __contributors__ = {}
# This is a url where the most recent plugin package can be downloaded.
__url__ = '' # 'http://supybot.com/Members/yourname/Pandorabots/download'
import config
import plugin
from . import config
from . import plugin
from imp import reload
reload(plugin) # In case we're being reloaded.
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!

148
Cleverbot/cleverbot.py Executable file → Normal file
View File

@ -36,101 +36,101 @@ import hashlib
import re
class ServerFullError(Exception):
pass
pass
ReplyFlagsRE = re.compile('<INPUT NAME=(.+?) TYPE=(.+?) VALUE="(.*?)">', re.IGNORECASE | re.MULTILINE)
class Session(object):
keylist=['stimulus','start','sessionid','vText8','vText7','vText6','vText5','vText4','vText3','vText2','icognoid','icognocheck','prevref','emotionaloutput','emotionalhistory','asbotname','ttsvoice','typing','lineref','fno','sub','islearning','cleanslate']
headers={}
headers['User-Agent']='Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0'
headers['Accept']='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
headers['Accept-Language']='en-us;q=0.8,en;q=0.5'
headers['X-Moz']='prefetch'
headers['Accept-Charset']='ISO-8859-1,utf-8;q=0.7,*;q=0.7'
headers['Referer']='http://www.cleverbot.com'
headers['Cache-Control']='no-cache, no-cache'
headers['Pragma']='no-cache'
keylist=['stimulus','start','sessionid','vText8','vText7','vText6','vText5','vText4','vText3','vText2','icognoid','icognocheck','prevref','emotionaloutput','emotionalhistory','asbotname','ttsvoice','typing','lineref','fno','sub','islearning','cleanslate']
headers={}
headers['User-Agent']='Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0'
headers['Accept']='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
headers['Accept-Language']='en-us;q=0.8,en;q=0.5'
headers['X-Moz']='prefetch'
headers['Accept-Charset']='ISO-8859-1,utf-8;q=0.7,*;q=0.7'
headers['Referer']='http://www.cleverbot.com'
headers['Cache-Control']='no-cache, no-cache'
headers['Pragma']='no-cache'
def __init__(self):
self.arglist=['','y','','','','','','','','','wsf','','','','','','','','','0','Say','1','false']
self.MsgList=[]
def __init__(self):
self.arglist=['','y','','','','','','','','','wsf','','','','','','','','','0','Say','1','false']
self.MsgList=[]
def Send(self):
data=encode(self.keylist,self.arglist)
digest_txt=data[9:29]
hash=hashlib.md5(digest_txt).hexdigest()
self.arglist[self.keylist.index('icognocheck')]=hash
data=encode(self.keylist,self.arglist)
req=urllib2.Request("http://www.cleverbot.com/webservicemin",data,self.headers)
f=urllib2.urlopen(req, timeout=9) #Needed to prevent supybot errors
reply=f.read()
return reply
def Send(self):
data=encode(self.keylist,self.arglist)
digest_txt=data[9:29]
hash=hashlib.md5(digest_txt).hexdigest()
self.arglist[self.keylist.index('icognocheck')]=hash
data=encode(self.keylist,self.arglist)
req=urllib2.Request("http://www.cleverbot.com/webservicemin",data,self.headers)
f=urllib2.urlopen(req, timeout=9) #Needed to prevent supybot errors
reply=f.read()
return reply
def Ask(self,q):
self.arglist[self.keylist.index('stimulus')]=q
if self.MsgList: self.arglist[self.keylist.index('lineref')]='!0'+str(len(self.MsgList)/2)
asw=self.Send()
self.MsgList.append(q)
answer = parseAnswers(asw)
for k,v in answer.iteritems():
try:
self.arglist[self.keylist.index(k)] = v
except ValueError:
pass
self.arglist[self.keylist.index('emotionaloutput')]=''
text = answer['ttsText']
self.MsgList.append(text)
return text
def Ask(self,q):
self.arglist[self.keylist.index('stimulus')]=q
if self.MsgList: self.arglist[self.keylist.index('lineref')]='!0'+str(len(self.MsgList)/2)
asw=self.Send()
self.MsgList.append(q)
answer = parseAnswers(asw)
for k,v in answer.iteritems():
try:
self.arglist[self.keylist.index(k)] = v
except ValueError:
pass
self.arglist[self.keylist.index('emotionaloutput')]=''
text = answer['ttsText']
self.MsgList.append(text)
return text
def parseAnswers(text):
d = {}
keys = ["text", "sessionid", "logurl", "vText8", "vText7", "vText6", "vText5", "vText4", "vText3",
"vText2", "prevref", "foo", "emotionalhistory", "ttsLocMP3", "ttsLocTXT",
"ttsLocTXT3", "ttsText", "lineRef", "lineURL", "linePOST", "lineChoices",
"lineChoicesAbbrev", "typingData", "divert"]
values = text.split("\r")
i = 0
for key in keys:
d[key] = values[i]
i += 1
return d
d = {}
keys = ["text", "sessionid", "logurl", "vText8", "vText7", "vText6", "vText5", "vText4", "vText3",
"vText2", "prevref", "foo", "emotionalhistory", "ttsLocMP3", "ttsLocTXT",
"ttsLocTXT3", "ttsText", "lineRef", "lineURL", "linePOST", "lineChoices",
"lineChoicesAbbrev", "typingData", "divert"]
values = text.split("\r")
i = 0
for key in keys:
d[key] = values[i]
i += 1
return d
def encode(keylist,arglist):
text=''
for i in range(len(keylist)):
k=keylist[i]; v=quote(arglist[i])
text+='&'+k+'='+v
text=text[1:]
return text
text=''
for i in range(len(keylist)):
k=keylist[i]; v=quote(arglist[i])
text+='&'+k+'='+v
text=text[1:]
return text
always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789' '_.-')
def quote(s, safe = '/'): #quote('abc def') -> 'abc%20def'
safe += always_safe
safe_map = {}
for i in range(256):
c = chr(i)
safe_map[c] = (c in safe) and c or ('%%%02X' % i)
res = map(safe_map.__getitem__, s)
return ''.join(res)
safe += always_safe
safe_map = {}
for i in range(256):
c = chr(i)
safe_map[c] = (c in safe) and c or ('%%%02X' % i)
res = map(safe_map.__getitem__, s)
return ''.join(res)
def main():
import sys
cb = Session()
import sys
cb = Session()
q = ''
while q != 'bye':
try:
q = raw_input("> ")
except KeyboardInterrupt:
print
sys.exit()
print cb.Ask(q)
q = ''
while q != 'bye':
try:
q = raw_input("> ")
except KeyboardInterrupt:
print
sys.exit()
print cb.Ask(q)
if __name__ == "__main__":
main()
main()

0
Cleverbot/config.py Executable file → Normal file
View File

227
Cleverbot/plugin.py Executable file → Normal file
View File

@ -25,119 +25,128 @@ import re, random, time
from htmlentitydefs import name2codepoint
class Cleverbot(callbacks.Plugin):
"""This plugin replies using the Cleverbot API upon intercepting an invalid command."""
threaded = True
callAfter = ['MoobotFactoids','Factoids','Infobot']
def __init__(self,irc):
self.__parent = super(Cleverbot,self)
self.__parent.__init__(irc)
self.nicks = {}
self.hashes = {}
self.sessions = {}
@staticmethod
def decode_htmlentities(s):
def substitute_entity(match):
ent = match.group(3)
if match.group(1) == "#": # number, decimal or hexadecimal
return unichr(int(ent)) if match.group(2) == '' else unichr(int('0x'+ent,16))
else: # name
cp = name2codepoint.get(ent)
return unichr(cp) if cp else match.group()
return re.compile(r'&(#?)(x?)(\w+);').subn(substitute_entity,s)[0]
@staticmethod
def _randHash():
return '%016x'%random.getrandbits(64)
@classmethod
def _post(cls,bot,hash,line,sess):
try:
m = sess.Ask(line)
except:
return None
if m:
return m
return None
@classmethod
def _identify(cls,bot,hash,name):
return cleverbot.Session()
def getHash(self,nick):
nick = nick.lower()
if nick not in self.nicks:
self.nicks[nick] = self._randHash()
return self.nicks[nick]
def getResponse(self,irc,msg,line):
hash = self.getHash(msg.nick)
args = (self.registryValue('bot'),hash)
if hash not in self.hashes or time.time()-self.hashes[hash] > 300:
sess = self._identify(*(args+(msg.nick,)))
self.sessions[hash] = sess
else:
sess = self.sessions[hash]
self.hashes[hash] = time.time()
line = re.compile(r'\b'+re.escape(irc.nick)+r'\b',re.I).sub('you',re.compile(r'^'+re.escape(irc.nick)+r'\S',re.I).sub('',line))
reply = self._post(*(args+(line,sess,)))
if reply is None:
return None
name = self.registryValue('name')
return reply
def invalidCommand(self,irc,msg,tokens):
try:
print "[Cleverbot] DEBUG: Channel is: "+str(irc.isChannel(msg.args[0]))
print "[Cleverbot] DEBUG: Message is: "+str(msg.args)
except:
print "[Cleverbot] ERROR... message not retrievable."
if irc.isChannel(msg.args[0]) and self.registryValue('react',msg.args[0]):
channel = msg.args[0]
print "[Cleverbot] Fetching response..."
reply = self.getResponse(irc,msg,ircutils.stripFormatting(msg.args[1]).strip())
print "[Cleverbot] Got response!"
if reply is not None:
print "[Cleverbot] DEBUG: Reply is: "+str(reply)
if self.registryValue('enable', channel):
"""This plugin replies using the Cleverbot API upon intercepting an invalid command."""
threaded = True
callAfter = ['MoobotFactoids','Factoids','Infobot']
def __init__(self,irc):
self.__parent = super(Cleverbot,self)
self.__parent.__init__(irc)
self.nicks = {}
self.hashes = {}
self.sessions = {}
@staticmethod
def decode_htmlentities(s):
def substitute_entity(match):
ent = match.group(3)
if match.group(1) == "#": # number, decimal or hexadecimal
return unichr(int(ent)) if match.group(2) == '' else unichr(int('0x'+ent,16))
else: # name
cp = name2codepoint.get(ent)
return unichr(cp) if cp else match.group()
return re.compile(r'&(#?)(x?)(\w+);').subn(substitute_entity,s)[0]
@staticmethod
def _randHash():
return '%016x'%random.getrandbits(64)
@classmethod
def _post(cls,bot,hash,line,sess):
try:
m = sess.Ask(line)
except:
return None
if m:
return m
return None
@classmethod
def _identify(cls,bot,hash,name):
return cleverbot.Session()
def getHash(self,nick):
nick = nick.lower()
if nick not in self.nicks:
self.nicks[nick] = self._randHash()
return self.nicks[nick]
def getResponse(self,irc,msg,line):
hash = self.getHash(msg.nick)
args = (self.registryValue('bot'),hash)
if hash not in self.hashes or time.time()-self.hashes[hash] > 300:
sess = self._identify(*(args+(msg.nick,)))
self.sessions[hash] = sess
else:
sess = self.sessions[hash]
self.hashes[hash] = time.time()
line = re.compile(r'\b'+re.escape(irc.nick)+r'\b',re.I).sub('you',re.compile(r'^'+re.escape(irc.nick)+r'\S',re.I).sub('',line))
reply = self._post(*(args+(line,sess,)))
if reply is None:
return None
name = self.registryValue('name')
return reply
def invalidCommand(self,irc,msg,tokens):
try:
self.log.debug('Channel is: "+str(irc.isChannel(msg.args[0]))')
self.log.debug("Message is: "+str(msg.args))
except:
self.log.error("message not retrievable.")
if irc.isChannel(msg.args[0]) and self.registryValue('react',msg.args[0]):
channel = msg.args[0]
self.log.debug("Fetching response...")
reply = self.getResponse(irc,msg,ircutils.stripFormatting(msg.args[1]).strip())
self.log.debug("Got response!")
if reply is not None:
self.log.debug("Reply is: "+str(reply))
if self.registryValue('enable', channel):
irc.reply(reply)
else:
irc.reply("My AI is down, sorry! :( I couldn't process what you said... blame it on a brain fart. :P")
elif (msg.args[0] == irc.nick) and self.registryValue('reactprivate',msg.args[0]):
err = ""
print "[Cleverbot] Fetching response..."
reply = self.getResponse(irc,msg,ircutils.stripFormatting(msg.args[1]).strip())
print "[Cleverbot] Got response!"
if reply is not None:
print "[Cleverbot] DEBUG: Reply is: "+str(reply)
if self.registryValue('enable', channel):
else:
irc.reply("My AI is down, sorry! :( I couldn't process what you said... blame it on a brain fart. :P")
elif (msg.args[0] == irc.nick) and self.registryValue('reactprivate',msg.args[0]):
err = ""
self.log.debug("Fetching response...")
reply = self.getResponse(irc,msg,ircutils.stripFormatting(msg.args[1]).strip())
self.log.debug("Got response!")
if reply is not None:
self.log.debug("Reply is: "+str(reply))
if self.registryValue('enable', channel):
irc.reply(reply)
else:
irc.reply("My AI is down, sorry! :( I couldn't process what you said... blame it on a brain fart. :P", err, None, True, None, None)
def Cleverbot(self,irc,msg,args,line):
"""<line>
Fetches response from Cleverbot
"""
reply = self.getResponse(irc,msg,line)
if reply is not None:
irc.reply('Cleverbot: %s'%reply)
else:
irc.reply('There was no response.')
Cleverbot = wrap(Cleverbot,['text'])
def doNick(self,irc,msg):
try:
del self.nicks[msg.nick.lower()]
except KeyError:
pass
self.nicks[msg.args[0].lower()] = self._randHash()
self._identify(self.registryValue('bot'),self.getHash(msg.args[0].lower()),msg.args[0])
# def doKick(self,irc,msg):
# del self.nicks[msg.args[1]]
# def doPart(self,irc,msg):
# del self.nicks[msg.nick.lower()]
def doQuit(self,irc,msg):
try:
del self.nicks[msg.nick.lower()]
except KeyError:
pass
else:
irc.reply("My AI is down, sorry! :( I couldn't process what you said... blame it on a brain fart. :P", err, None, True, None, None)
def Cleverbot(self,irc,msg,args,line):
"""<line>
Fetches response from Cleverbot
"""
reply = self.getResponse(irc,msg,line)
if reply is not None:
irc.reply('Cleverbot: %s'%reply)
else:
irc.reply('There was no response.')
Cleverbot = wrap(Cleverbot,['text'])
def doNick(self,irc,msg):
try:
del self.nicks[msg.nick.lower()]
except KeyError:
pass
self.nicks[msg.args[0].lower()] = self._randHash()
self._identify(self.registryValue('bot'),self.getHash(msg.args[0].lower()),msg.args[0])
# def doKick(self,irc,msg):
# del self.nicks[msg.args[1]]
# def doPart(self,irc,msg):
# del self.nicks[msg.nick.lower()]
def doQuit(self,irc,msg):
try:
del self.nicks[msg.nick.lower()]
except KeyError:
pass
Class = Cleverbot
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:

0
Cleverbot/test.py Executable file → Normal file
View File