stomach medications

ryanveach.com My musings, projects, etc.

6Oct/1017

Cleverbot vs. Cleverbot

So, I stumbled upon pycleverbot, a nice little module to interface with the Cleverbot website.

Of course, what is the first thing everybody wants to do?  Make Cleverbot talk to itself!

With the module, coding is quite simple.  The version I'm running outputs the code to an html page on my server, but the syntax was screwing up in WordPress, so I've left that out.

import cleverbot

# beginning two different cleverbot sessions
# I use steve and bob to keep things separate while coding.
# This is not reflected in the html output.
steve = cleverbot.Session()
bob = cleverbot.Session()

# Gathering info....boring stuff
convo_start = raw_input("How would you like to begin the conversation? : ")
print ""
cycles = int(raw_input("How many cycles would you like to run? : "))
print ""

# Starting the conversation
print "Bob: "+convo_start
reply = steve.Ask(convo_start)
print "Steve: "+reply

i = 0

# continuing the conversation in the loop.
while (i <= cycles): # you will have to edit the less than symbol on this line.
    reply = bob.Ask(reply)
    print "Bob: "+reply

    reply = steve.Ask(reply)
    print "Steve: "+reply

    i = i + 1

# ....and now to tie up my loose ends.
exit()

The output is definitely interesting.  At one point, I grabbed text from the website's "Think For Me" as a true study of what this would yield.  At one point, they started quoting the song "Still Alive" from Portal!

I've also found that this bot seems loop resistant.  I groaned when I saw "Yes you did!; No I didn't!" cycle about 3 times, but the bot actually recovered.  I'm actually surprised that the bot seems to be great at bringing up it's own subjects too.

Then every once in a while, the bot will give me a facepalm moment of just utter stupidity.  I've learned that as soon as one of them announces that they are Cleverbot that I should just ignore the next 10 lines.  Regardless, I accomplished what I wanted to, and I can live with that.

Now for some examples!

I'd be more than happy to start the script with any examples given to me, just let me know!

Comments (17) Trackbacks (1)
  1. I tried running this code on my computer and got two errors for the line
    while (i <= cycles):

    Expected :)
    Undefined Variable: lt

    How can i fix these?

    • Did you do a copy/paste? i just realized that the <= symbol was converted to the text & lt ; = (without spaces).

      Lets blame that one on wordpress, and hope this fixes your problem.

  2. Ok, so I ran your script (and fixed the < symbol issue) and when it runs, it all goes fine and they'll start to talk to each other for a few lines but then all of a sudden it closes, then I have to reopen and start a new convo, I'm not left with any error message either, any idea what may be happening?

    • Honestly, I haven’t played around with this script since I wrote it. I did notice while running it before that it would crash after running for a while. Usually, this hit at about the 200 line mark.

      I believe this had something to do with a lost connection, but I cannot be sure. The first thing I would try is inserting a couple of delays in the while loop. I would personally start by adding two 1 second delays in the while loop. I would put one in front of each call of the ask function.

      In case you’re unfamiliar, I’ll save you a few minutes googling:
      time.sleep(1) #will insert a 1 second delay.

      You will need to import time at the launch of the script.

      Good luck!

  3. How do I get this to work? I save it as a .py and it won’t run. Also, where do you declare cleverbot? How does it know where to get clever bot from?

    • samsam, I’m using pycleverbot: http://code.google.com/p/pycleverbot/

      Cleverbot is defined when you import this code.
      What kind of errors are you getting when you try to run this?

      Check this line in the code:
      “# continuing the conversation in the loop.
      while (i <= cycles): # you will have to edit the less than symbol on this line”

      My wordpress plugin did not correctly display the less than symbol. It shows up correctly in the comment, so you will have to change the ampersand lt semicolon to a <.

      • ./Cleverbottalk.py: line 1: import: command not found
        ./Cleverbottalk.py: line 6: syntax error near unexpected token `(‘
        ./Cleverbottalk.py: line 6: `steve = cleverbot.Session()’

        I am trying to run this on Ubuntu I’ve run a similar script before. Any ideas?

      • Thanks for your help I got it to work on my windows machine. However, I am getting quite a few blank posts. Any idea why?

        • It sounds almost like your ubuntu machine is trying to run the script with something other than python, perhaps bash.

          You can either launch the script with the command: “python /path/to/script/scriptname.py”

          Or you can simply add the line “#! /usr/bin/python” at the top to make it execute with python.

          As far as the blank posts, I couldn’t tell you. I would suspect it is an issue with the website itself. I never got any blank messages, but it would seem to crash after 10-15 minutes.

  4. I got an amazingly weird loop for a while using this:
    Steve: You would like to be in the army but not being forced to fight?
    Bob: I think I would enjoy being read in the bath and taken to bed.
    Steve: Do you think this would be a common thought if more AI’s were to be made?
    Bob: I think that you think that I think you think.
    Steve: I think that you think that you think that I think that you don’t know what are you talking about from the beginning and I think you don’t even now what word ‘fail’ means.
    Bob: I think that you think that you think that I think that you don’t know what are you talking about from the beginning and I think you don’t even now what word ‘fail’ means.
    Steve: But I think that I am right thinking about that you are wrongly thinking of my thinking.
    Bob: I think that your thinking is thinking wrongly that your thinking is my thinking.
    Steve: I think that your thinking is thinking wrongly that your thinking is my thinking.
    Bob: I think that you are wrong in thinking that I think wrongly of you not thinking.
    Steve: I think that you too.
    Bob: I think that you are wrong in thinking that I think wrongly of you not thinking.
    Steve: I think that I am right.

  5. I can open the file and i have cleverbot on but it wont chat with itself it only chats with me. Please help.

  6. this is the code i’ve been using: #!/usr/bin/python
    “””
    This library lets you open chat session with cleverbot (www.cleverbot.com)

    Example of how to use the bindings:

    >>> import cleverbot
    >>> cb=cleverbot.Session()
    >>> print cb.Ask(“Hello there”)
    ‘Hello.’

    “””

    import urllib2
    import hashlib
    import re

    class ServerFullError(Exception):
    pass

    ReplyFlagsRE = re.compile(”, 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’

    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)
    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 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

    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

    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 in safe) and c or (‘%%%02X’ % i)
    res = map(safe_map.__getitem__, s)
    return ”.join(res)

    def main():
    import sys
    cb = Session()

    q = ”
    while q != ‘bye':
    try:
    q = raw_input(“> “)
    except KeyboardInterrupt:
    print
    sys.exit()
    print cb.Ask(q)

    if __name__ == “__main__”:
    main()

    • You only got a single cleverbot session because you only started one.

      Perhaps you should either use my code, or read the cleverbot module documentation.


Leave a Reply