Advertisement
jalla2000

Cleverbot-Pidgin-bot

Sep 3rd, 2011
1,378
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.60 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import urllib2
  4. import md5
  5. import re
  6. import dbus, gobject
  7. from dbus.mainloop.glib import DBusGMainLoop
  8. from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
  9.  
  10. class ServerFullError(Exception):
  11.     pass
  12.  
  13. ReplyFlagsRE = re.compile('<INPUT NAME=(.+?) TYPE=(.+?) VALUE="(.*?)">', re.IGNORECASE | re.MULTILINE)
  14.  
  15. class CleverbotSession:
  16.     keylist=['stimulus','start','sessionid','vText8','vText7','vText6','vText5','vText4','vText3','vText2','icognoid','icognocheck','prevref','emotionaloutput','emotionalhistory','asbotname','ttsvoice','typing','lineref','sub','islearning','cleanslate']
  17.     headers={}
  18.     headers['User-Agent']='Mozilla/5.0 (X11; U; Linux x86_64; it; rv:1.9.1.8) Gecko/20100214 Ubuntu/9.10 (karmic) Firefox/3.5.8'
  19.     headers['Accept']='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
  20.     headers['Accept-Language']='it-it,it;q=0.8,en-us;q=0.5,en;q=0.3'
  21.     headers['X-Moz']='prefetch'
  22.     headers['Accept-Charset']='ISO-8859-1,utf-8;q=0.7,*;q=0.7'
  23.     headers['Referer']='http://www.cleverbot.com'
  24.     headers['Cache-Control']='no-cache, no-cache'
  25.     headers['Pragma']='no-cache'
  26.  
  27.     def __init__(self):
  28.         self.arglist=['','y','','','','','','','','','wsf','','','','','','','','','Say','1','false']
  29.         self.MsgList=[]
  30.  
  31.     def Send(self):
  32.         data=encode(self.keylist,self.arglist)
  33.         digest_txt=data[9:29]
  34.         hash=md5.new(digest_txt).hexdigest()
  35.         self.arglist[self.keylist.index('icognocheck')]=hash
  36.         data=encode(self.keylist,self.arglist)
  37.         req=urllib2.Request("http://www.cleverbot.com/webservicefrm",data,self.headers)
  38.         f=urllib2.urlopen(req)
  39.         reply=f.read()
  40.         return reply
  41.  
  42.     def Ask(self,q):
  43.         print "Asking cleverbot: %s" % q
  44.         self.arglist[self.keylist.index('stimulus')]=q
  45.         if self.MsgList: self.arglist[self.keylist.index('lineref')]='!0'+str(len(self.MsgList)/2)
  46.         asw=self.Send()
  47.         if '<meta name="description" content="Jabberwacky server maintenance">' in asw: raise ServerFullError, "The Cleverbot server answered with full load error"
  48.         self.MsgList.append(q)
  49.         answ_dict=GetAnswerArgs(asw)
  50.         for k in self.keylist:
  51.             if k in answ_dict: self.arglist[self.keylist.index(k)]=answ_dict[k]
  52.         self.arglist[self.keylist.index('emotionaloutput')]=''
  53.         reply_i=asw.find('<!-- Begin Response !-->')+25
  54.         reply_s=asw.find('<!-- End Response !-->')-1
  55.         text=asw[reply_i:reply_s]
  56.         self.MsgList.append(text)
  57.         return text
  58.  
  59. def GetAnswerArgs(text):
  60.     results=ReplyFlagsRE.findall(text)
  61.     list={}
  62.     for r in results: list[r[0]]=r[2]
  63.     return list
  64.  
  65. def encode(keylist,arglist):
  66.     text=''
  67.     for i in range(len(keylist)):
  68.         k=keylist[i]; v=quote(arglist[i])
  69.         text+='&'+k+'='+v
  70.     text=text[1:]
  71.     return text
  72.  
  73. always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  74.                'abcdefghijklmnopqrstuvwxyz'
  75.                '0123456789' '_.-')
  76. def quote(s, safe = '/'):   #quote('abc def') -> 'abc%20def'
  77.     safe += always_safe
  78.     safe_map = {}
  79.     for i in range(256):
  80.         c = chr(i)
  81.         safe_map[c] = (c in safe) and c or  ('%%%02X' % i)
  82.     res = map(safe_map.__getitem__, s)
  83.     return ''.join(res)
  84.  
  85. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  86. bus = dbus.SessionBus()
  87. obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
  88. purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
  89.  
  90. conversations = {}
  91.  
  92. def htmlClean(pidginHtml):
  93.     soup = BeautifulSoup(pidginHtml)
  94.     pidginHtml = soup.findAll('font')[-1].contents
  95.     return str(BeautifulStoneSoup(pidginHtml[0], convertEntities=BeautifulStoneSoup.ALL_ENTITIES))
  96.  
  97. def messageDisplayed(account, who, message, conversation, flags):
  98.     global purple
  99.     direction = "Incoming"
  100.     if flags != 2:
  101.         direction = "Outgoing"
  102.     print "Account/ConvId(%s/%s): %s message - %s said: \"%s\"" % (account, conversation, direction, who, message)
  103.     username = purple.PurpleAccountGetUsername(account)
  104.     if flags == 2 and username == "youraccount@hotmail.com":
  105.         if conversation not in conversations.keys():
  106.             conversations[conversation] = CleverbotSession()
  107.             purple.PurpleConvImSend(purple.PurpleConvIm(conversation), u'Hi! I\'m Amy! Pål is not around right now...')
  108.         else:
  109.             question = htmlClean(message)
  110.             response = conversations[conversation].Ask(question)
  111.             print 'Asked: "%s" Response: "%s"' % (question, response)
  112.             purple.PurpleConvImSend(purple.PurpleConvIm(conversation), response)
  113.  
  114. bus.add_signal_receiver(messageDisplayed,
  115.                         dbus_interface="im.pidgin.purple.PurpleInterface",
  116.                         signal_name="DisplayedImMsg")
  117.  
  118. loop = gobject.MainLoop()
  119. loop.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement